-(NSInteger)numberOfSectionsInTableView:(UITableView*)tableView{// Return the number of sections.return4;}-(NSInteger)tableView:(UITableView*)tableViewnumberOfRowsInSection:(NSInteger)section{// Return the number of rows in the section.if(section==0){return1;}if(section==1){return2;}if(section==2){return4;}if(section==3){return1;}return0;}
-(UITableViewCell*)tableView:(UITableView*)tableViewcellForRowAtIndexPath:(NSIndexPath*)indexPath{staticNSString*CellIdentifier=@"Cell";PrettyTableViewCell*cell=[tableViewdequeueReusableCellWithIdentifier:CellIdentifier];if(cell==nil){cell=[[PrettyTableViewCellalloc]initWithStyle:UITableViewCellStyleDefaultreuseIdentifier:CellIdentifier];switch(indexPath.section){case0:switch(indexPath.row){case0:[selfprepareNameCell:cell];break;}break;default:break;}//设置圆角弧度和阴影cell.cornerRadius=5;cell.shadowOpacity=0.07;cell.backgroundColor=[UIColorwhiteColor];//设置选择时候的颜色cell.selectionGradientStartColor=[UIColorcolorWithRed:248.0/255.0green:244.0/255.0blue:239.0/255.0alpha:1];cell.SelectionGradientEndColor=[UIColorcolorWithRed:248.0/255.0green:244.0/255.0blue:239.0/255.0alpha:1];// Configure the cell...[cellprepareForTableView:tableViewindexPath:indexPath];}returncell;}
Elixir处理结尾很简单,就是没有符号,和ruby一样,所有方法都用end结束, Less is More。
123
def hello
IO.puts "hello world"
end
比较运算符
Erlang
12345678
X > Y X is greater than Y.
X < Y X is less than Y.
X =< Y X is equal to or less than Y.
X >= Y X is greater than or equal to Y.
X == Y X is equal to Y.
X /= Y X is not equal to Y.
X =:= Y X is identical to Y.
X =/= Y X is not identical to Y
a === b # strict equality (so 1 === 1.0 is false)
a !== b # strict inequality (so 1 !== 1.0 is true)
a == b # value equality (so 1 == 1.0 is true)
a != b # value inequality (so 1 != 1.0 is false)
a > b # normal comparison
a >= b # :
a < b # :
a <= b # :
requireFile.expand_path('../boot',__FILE__)require'rails/all'ifdefined?(Bundler)# If you precompile assets before deploying to production, use this lineBundler.require(*Rails.groups(:assets=>%w(development test)))# If you want your assets lazily compiled in production, use this line# Bundler.require(:default, :assets, Rails.env)endmoduleRailsStudyclassApplication<Rails::Application# Settings in config/environments/* take precedence over those specified here.# Application configuration should go into files in config/initializers# -- all .rb files in that directory are automatically loaded.# Custom directories with classes and modules you want to be autoloadable.# config.autoload_paths += %W(#{config.root}/extras)# Only load the plugins named here, in the order given (default is alphabetical).# :all can be used as a placeholder for all plugins not explicitly named.# config.plugins = [ :exception_notification, :ssl_requirement, :all ]# Activate observers that should always be running.# config.active_record.observers = :cacher, :garbage_collector, :forum_observer# Set Time.zone default to the specified zone and make Active Record auto-convert to this zone.# Run "rake -D time" for a list of tasks for finding time zone names. Default is UTC.# config.time_zone = 'Central Time (US & Canada)'# The default locale is :en and all translations from config/locales/*.rb,yml are auto loaded.# config.i18n.load_path += Dir[Rails.root.join('my', 'locales', '*.{rb,yml}').to_s]config.i18n.default_locale="zh-CN"# Configure the default encoding used in templates for Ruby 1.9.config.encoding="utf-8"# Configure sensitive parameters which will be filtered from the log file.config.filter_parameters+=[:password]# Enable escaping HTML in JSON.config.active_support.escape_html_entities_in_json=true# Use SQL instead of Active Record's schema dumper when creating the database.# This is necessary if your schema can't be completely dumped by the schema dumper,# like if you have constraints or database-specific column types# config.active_record.schema_format = :sql# Enforce whitelist mode for mass assignment.# This will create an empty whitelist of attributes available for mass-assignment for all models# in your app. As such, your models will need to explicitly whitelist or blacklist accessible# parameters by using an attr_accessible or attr_protected declaration.config.active_record.whitelist_attributes=true# Enable the asset pipelineconfig.assets.enabled=true# Version of your assets, change this if you want to expire all your assetsconfig.assets.version='1.0'endend
moduleRailsclassRailtiemoduleConfigurableextendActiveSupport::ConcernmoduleClassMethodsdelegate:config,:to=>:instancedefinherited(base)raise"You cannot inherit from a #{self.superclass.name} child"enddefinstance@instance||=newend...endendendend
definitializer(name,opts={},&blk)raiseArgumentError,"A block must be passed when defining an initializer"unlessblkopts[:after]||=initializers.last.nameunlessinitializers.empty?||initializers.find{|i|i.name==opts[:before]}initializers<<Initializer.new(name,nil,opts,&blk)end
我们写的Gem包也可以是一个Engine应用,里面可以包含自己的controller,model,view文件,文件结构也可以和rails的文件结构一样,这样的构架很方便做一些通用的功能包,为减少重复代码提供了极大的方便。Engine本身还是有很多内容可以说的,关于如何应用他可以看看这个教程:Getting Started with Engines。
definitialize!(group=:default)#:nodoc:raise"Application has been already initialized."if@initializedrun_initializers(group,self)@initialized=trueselfend
defdefault_middleware_stackActionDispatch::MiddlewareStack.new.tapdo|middleware|ifrack_cache=config.action_controller.perform_caching&&config.action_dispatch.rack_cacherequire"action_dispatch/http/rack_cache"middleware.use::Rack::Cache,rack_cacheendifconfig.force_sslrequire"rack/ssl"middleware.use::Rack::SSL,config.ssl_optionsendifconfig.serve_static_assetsmiddleware.use::ActionDispatch::Static,paths["public"].first,config.static_cache_controlendmiddleware.use::Rack::Lockunlessconfig.allow_concurrencymiddleware.use::Rack::Runtimemiddleware.use::Rack::MethodOverridemiddleware.use::ActionDispatch::RequestIdmiddleware.use::Rails::Rack::Logger,config.log_tags# must come after Rack::MethodOverride to properly log overridden methodsmiddleware.use::ActionDispatch::ShowExceptions,config.exceptions_app||ActionDispatch::PublicExceptions.new(Rails.public_path)middleware.use::ActionDispatch::DebugExceptionsmiddleware.use::ActionDispatch::RemoteIp,config.action_dispatch.ip_spoofing_check,config.action_dispatch.trusted_proxiesifconfig.action_dispatch.x_sendfile_header.present?middleware.use::Rack::Sendfile,config.action_dispatch.x_sendfile_headerendunlessconfig.cache_classesapp=selfmiddleware.use::ActionDispatch::Reloader,lambda{app.reload_dependencies?}endmiddleware.use::ActionDispatch::Callbacksmiddleware.use::ActionDispatch::Cookiesifconfig.session_storeifconfig.force_ssl&&!config.session_options.key?(:secure)config.session_options[:secure]=trueendmiddleware.useconfig.session_store,config.session_optionsmiddleware.use::ActionDispatch::Flashendmiddleware.use::ActionDispatch::ParamsParsermiddleware.use::ActionDispatch::Headmiddleware.use::Rack::ConditionalGetmiddleware.use::Rack::ETag,"no-cache"ifconfig.action_dispatch.best_standards_supportmiddleware.use::ActionDispatch::BestStandardsSupport,config.action_dispatch.best_standards_supportendendend
defstart(&block)raiseServerError,"already started."if@status!=:Stopserver_type=@config[:ServerType]||SimpleServerserver_type.start{@logger.info\"#{self.class}#start: pid=#{$$} port=#{@config[:Port]}"call_callback(:StartCallback)thgroup=ThreadGroup.new@status=:Runningwhile@status==:Runningbeginifsvrs=IO.select(@listeners,nil,nil,2.0)svrs[0].each{|svr|@tokens.pop# blocks while no token is there.ifsock=accept_client(svr)sock.do_not_reverse_lookup=config[:DoNotReverseLookup]th=start_thread(sock,&block)th[:WEBrickThread]=truethgroup.add(th)else@tokens.push(nil)end}endrescueErrno::EBADF,IOError=>ex# if the listening socket was closed in GenericServer#shutdown,# IO::select raise it.rescueException=>exmsg="#{ex.class}: #{ex.message}\n\t#{ex.backtrace[0]}"@logger.errormsgendend@logger.info"going to shutdown ..."thgroup.list.each{|th|th.joinifth[:WEBrickThread]}call_callback(:StopCallback)@logger.info"#{self.class}#start done."@status=:Stop}end
defservice(req,res)ifreq.unparsed_uri=="*"ifreq.request_method=="OPTIONS"do_OPTIONS(req,res)raiseHTTPStatus::OKendraiseHTTPStatus::NotFound,"`#{req.unparsed_uri}' not found."endservlet,options,script_name,path_info=search_servlet(req.path)raiseHTTPStatus::NotFound,"`#{req.path}' not found."unlessservletreq.script_name=script_namereq.path_info=path_infosi=servlet.get_instance(self,*options)@logger.debug(format("%s is invoked.",si.class.name))si.service(req,res)end
# model class# define attr_accessor coordsclassUser<ActiveRecord::Baseattr_accessor:coordsmount_uploader:icon,AvatarUploaderend# controller# pass the params to @user.coordsdefcrop_icon@user.coords=params[:coords]@user.icon=File.open(path)@user.saveredirect_to:action=>'basic'end# Uploader# the model in the function is same as @user in controll,# and can be invoked inside of process method defcrop_areamanipulate!do|img|unlessmodel.coords.nil?coords=JSON.parse(model.coords)img.crop("#{coords['w']}x#{coords['h']}+#{coords['x']}+#{coords['y']}")endimg=yield(img)ifblock_given?imgendend
#!/usr/bin/env ruby## This file was generated by RubyGems.## The application 'railties' is installed as part of a gem, and# this file is here to facilitate running it.#require'rubygems'version=">= 0"ifARGV.firststr=ARGV.firststr=str.dup.force_encoding("BINARY")ifstr.respond_to?:force_encodingpstrifstr=~/\A_(.*)_\z/version=$1ARGV.shiftendendgem'railties',versionloadGem.bin_path('railties','rails',version)
require'rbconfig'require'rails/script_rails_loader'# If we are inside a Rails application this method performs an exec and thus# the rest of this script is not run.Rails::ScriptRailsLoader.exec_script_rails!require'rails/ruby_version_check'Signal.trap("INT"){puts;exit(1)}ifARGV.first=='plugin'ARGV.shiftrequire'rails/commands/plugin_new'elserequire'rails/commands/application'end
moduleRailsmoduleScriptRailsLoaderRUBY=File.join(*RbConfig::CONFIG.values_at("bindir","ruby_install_name"))+RbConfig::CONFIG["EXEEXT"]SCRIPT_RAILS=File.join('script','rails')defself.exec_script_rails!cwd=Dir.pwdreturnunlessin_rails_application?||in_rails_application_subdirectory?execRUBY,SCRIPT_RAILS,*ARGVifin_rails_application?...rescueSystemCallError# could not chdir, no problem just returnend...endend
#!/usr/bin/env ruby# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.APP_PATH=File.expand_path('../../config/application',__FILE__)requireFile.expand_path('../../config/boot',__FILE__)require'rails/commands'
when'server'# Change to the application's path if there is no config.ru file in current dir.# This allows us to run script/rails server from other directories, but still get# the main config.ru and properly set the tmp directory.Dir.chdir(File.expand_path('../../',APP_PATH))unlessFile.exists?(File.expand_path("config.ru"))require'rails/commands/server'Rails::Server.new.tap{|server|# We need to require application after the server sets environment,# otherwise the --environment option given to the server won't propagate.requireAPP_PATHDir.chdir(Rails.application.root)server.start}
defstarturl="#{options[:SSLEnable]?'https':'http'}://#{options[:Host]}:#{options[:Port]}"puts"=> Booting #{ActiveSupport::Inflector.demodulize(server)}"puts"=> Rails #{Rails.version} application starting in #{Rails.env} on #{url}"puts"=> Call with -d to detach"unlessoptions[:daemonize]trap(:INT){exit}puts"=> Ctrl-C to shutdown server"unlessoptions[:daemonize]#Create required tmp directories if not found%w(cache pids sessions sockets).eachdo|dir_to_make|FileUtils.mkdir_p(Rails.root.join('tmp',dir_to_make))endsuperensure# The '-h' option calls exit before @options is set.# If we call 'options' with it unset, we get double help banners.puts'Exiting'unless@options&&options[:daemonize]end
这时你就知道在 rails s 的时候显示的几行文字是从这里打印出来的了,最后他会调用 Rack::Server.start 方法,也就是父类方法.
原因非常的简单,你可以这样想:这个? extends T 通配符告诉编译器我们在处理一个类型T的子类型,但我们不知道这个子类型究竟是什么。因为没法确定,为了保证类型安全,我们就不允许往里面加入任何这种类型的数据。另一方面,因为我们知道,不论它是什么类型,它总是类型T的子类型,当我们在读取数据时,能确保得到的数据是一个T类型的实例:
1
Fruit get = fruits.get(0);
? super
使用 ? super 通配符一般是什么情况?让我们先看看这个:
12
List<Fruit> fruits = new ArrayList<Fruit>();
List<? super Apple> = fruits;